【问题标题】:How to use mysqli::bind_param with an array as the second parameter如何使用带有数组作为第二个参数的 mysqli::bind_param
【发布时间】:2018-11-12 04:26:18
【问题描述】:

这个查询应该在'users'表中插入一个新用户

$user = DB::getInstance()->insert('users', array(
        'username' => 'jim',
        'password' => 'pass',
        'salt' => 'salt'
       )
);

对应的insert()

public function insert($table, $fields = array())
{
    if (count($fields)) {
        $keys   = array_keys($fields);
        $values = null;
        $x      = 1;
        foreach ($fields as $field) {
            $values .= "?";
            if ($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }
        $sql = "INSERT INTO users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
        echo $sql;
        if($this->queryDB($sql,$fields)){
            echo "its good";
            return true;
        }else{
            echo "bad query";
        }
    }
    return false;
}

尝试绑定查询值数组 ($param) 作为 bind_param 函数的第二个参数

    $stmt = $this->mysqli->prepare($pattern);
    $stmt->bind_param("sss", $param);
    $stmt->execute();

此代码不断返回“mysqli_stmt::bind_param(): 类型定义字符串中的元素数与绑定变量数不匹配”错误。

我也尝试过 call_user_func_array,但总是遇到同样的错误。我做错了什么?

【问题讨论】:

    标签: php arrays mysqli prepared-statement bindparam


    【解决方案1】:

    从 PHP 5.6 开始,您可以使用 splat 运算符...

    $stmt->bind_param("sss", ...$param);
    

    【讨论】:

    • 添加“...”会导致以下错误“无法使用字符串键解压数组”。我也试过 call_user func_array 没有成功。
    • 假设字段顺序正确,您可以使用array_values($param)
    【解决方案2】:

    如果您无法让 splat 运算符工作,您可能必须将 PHP 版本更新为至少 PHP 5.6 才能传递这样的数组:

    bind_param("sss", ...$array); 
    

    使用以下命令检查您在 linux 上的版本:

    php --version
    

    我在 Centos 7 上将我的更新到 PHP 7.2,这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 2017-07-11
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      相关资源
      最近更新 更多