Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 363
qb1234 Avatar asked Jun 02 '18 04:06

qb1234


People also ask

What is Mysqli Bind_param () function in PHP?

The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name.

How to use bindParam in PHP?

$stmt->bind_param("sss", $firstname, $lastname, $email); This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.

How to INSERT data using prepared statement in PHP?

mysqli_connect_error()); } // Prepare an insert statement $sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email); // Set ...

What is Mysqli_prepare?

The prepare() / mysqli_prepare() function is used to prepare an SQL statement for execution.


1 Answers

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

$stmt->bind_param("sss", ...$param);
like image 190
Nigel Ren Avatar answered Sep 20 '22 23:09

Nigel Ren