Home > Backend Development > PHP Tutorial > How to Fix the 'mysqli_stmt::bind_param() Expected a Reference' Error?

How to Fix the 'mysqli_stmt::bind_param() Expected a Reference' Error?

Barbara Streisand
Release: 2024-12-01 17:25:14
Original
516 people have browsed it

How to Fix the

Resolving the "mysqli bind_param() Expected a Reference" Error

When encountering the error "Parameter 3 to mysqli_stmt::bind_param() expected to be a reference, value given," it indicates that the $params array is not properly configured for binding. To resolve this, it is crucial to understand the requirements for mysqli_stmt_bind_param().

The error arises because mysqli_stmt_bind_param() expects the parameters to be passed by reference. However, the $params array contains value copies, which are not references. To correct this, you must convert the values in $params to references using the following method:

function refValues($arr) {
    if (strnatcmp(phpversion(), '5.3') >= 0) { // Reference is required for PHP 5.3+
        $refs = array();
        foreach ($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}
Copy after login

Once the $params array contains references to the values, you can bind the parameters correctly using the following code:

PDO:

$query = "INSERT INTO test (id,row1,row2,row3) VALUES (?,?,?,?)";
$params = array(1, "2", "3", "4");
$param_type = "isss";
$sql_stmt = mysqli_prepare($mysqli, $query);
call_user_func_array('mysqli_stmt_bind_param', array_merge(array($sql_stmt, $param_type), refValues($params)));
mysqli_stmt_execute($sql_stmt);
Copy after login

OOP:

$insert_stmt = $mysqli->prepare($query);
array_unshift($params, $param_type);
call_user_func_array(array($insert_stmt, 'bind_param'), refValues($params));
$insert_stmt->execute();
Copy after login

The above is the detailed content of How to Fix the 'mysqli_stmt::bind_param() Expected a Reference' Error?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template