【问题标题】:Bind Variable Amount of Parameters in Prepared Statement在准备好的语句中绑定可变数量的参数
【发布时间】:2015-06-16 14:47:43
【问题描述】:

我目前正在尝试构建一个小的通用函数来进行插入。我的目标是传递表格、列、值和类型来填充插入。

我唯一的问题是声明:

$stmt -> bind_param($types, $var1, $var2 ...);

我基本上需要的是这样的:

$stmt -> bind_param($types, $array);

这是我到现在得到的:

function insert($into, $columns, $values, $types) {
    global $connection;

    // Check Correct Length
    if(count($columns) != count($values) ||
       count($columns) != count($types)) {
           return false;
       }

    $count = count($columns);

    $column_string = "";
    $value_string = "";
    $value_types = "";

    for($i = 0; $i < $count; $i++) {
        $column_string .= $columns[$i];
        $value_types .= $types[$i];

        $value_string .= '?';

        if($i + 1 < $count) {
            $column_string .= ',';
            $value_string .= ',';
        }
    }

    $sql = "INSERT INTO $into ($column_string) VALUES ($value_string)";

    // Execute Statement
    if($stmt = $connection -> prepare($sql)) {

        // $stmt -> bind_param("sss", $transaction, $email, $status);
        // What to do here?

        $stmt -> execute();

        $stmt -> close();
    }

SQL 语句看起来已经很好了。类型也准备好了 - 我只需要一种动态绑定参数的方法......

【问题讨论】:

  • 你不能。 bindparam 是 1:1 映射。您可以使用 execute() 中的数组选项一次性传入所有内容。 $stmt-&gt;execute(array(':foo' =&gt; 'bar', ....));
  • 你能给我更多的信息吗?这样做有负面影响吗?
  • 好吧,这只有助于执行查询。如果你想绑定结果值,你会遇到很多 bindparam() 调用。

标签: php mysqli prepared-statement


【解决方案1】:

我假设,在 $columns 中定义为 $columns = array('col1', 'col2'/*...*/);$values$values = array($val1, $val2/*...*/);

我会为列名转义创建函数。

$escapeCols = function($column) { return sprintf('%s', $column); };

另一个创建的函数?占位符

$placeholders = function ($values) { return array_fill(0, count($values), '?'); }

您可以准备查询

$sql = sprintf( 'INSERT INTO %s (%s) VALUES (%s)', $table, implode(', ', array_map($escapeCols, $columns), implode(', ', $placeholders($values)) );

然后你可以拨打execute

$stmt = $connection->prepare($sql); $stmt->execute($values);

如果您将 $values 定义为

,则可以轻松转换这种方式

$values = array('col1' =&gt; $va1, 'col2' =&gt; $val2);

【讨论】:

  • 首先谢谢 - 我试过这个但收到以下错误:警告:mysqli_stmt::execute() 需要 0 个参数,1 在 /var/www/virtual/.../helper 中给出.php 在第 126 行
  • 对不起,我错过了你正在使用 mysqli。我的评论适用于 pdo。哪个具有更好的功能。
猜你喜欢
  • 2010-09-05
  • 2019-11-09
  • 2013-12-13
  • 2016-05-22
  • 2016-08-30
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
相关资源
最近更新 更多