How to use mysqli::bind_param with an array as the second parameter

时光毁灭记忆、已成空白 提交于 2019-12-02 01:11:33

问题


This query is supposed to insert a new user into the 'users' table

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

Corresponding 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;
}

Attempting to bind query an array of values ($param) as the second parameter of bind_param function

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

This code keeps returning "mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables" error.

I have also tried call_user_func_array, but keep getting the same error. What ami I doing wrong?


回答1:


As of PHP 5.6, you can use the splat operator ...

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


来源:https://stackoverflow.com/questions/50653406/how-to-use-mysqlibind-param-with-an-array-as-the-second-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!