Home > Backend Development > PHP Tutorial > How to Resolve the 'mysqli_stmt::bind_param() Expected to be a Reference, Value Given' Error?

How to Resolve the 'mysqli_stmt::bind_param() Expected to be a Reference, Value Given' Error?

Susan Sarandon
Release: 2024-12-01 14:04:10
Original
991 people have browsed it

How to Resolve the

mysqli bind_param() Parameter Reference Error: Resolving with RefValues Function

Why am I receiving the error "mysqli_stmt::bind_param() expected to be a reference, value given"?

The error "mysqli_stmt::bind_param() expected to be a reference, value given" occurs when you try to pass a variable or value by value to the bind_param() method, which expects a reference. This issue can arise when using call_user_func_array() to pass multiple parameters to bind_param().

Understanding the Issue

MySQLi functions, including bind_param(), require variables passed as references for optimal performance. However, call_user_func_array() expects parameters as values. This mismatch in expectations leads to the error.

Solution: Using RefValues() function

To resolve this issue, you can use the refValues() function, which converts an array of values into an array of references. Here's an example:

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

$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

Alternative Solution: Using Spread Operator

In newer versions of PHP, you can use the spread operator (...) to convert an array of values into an array of references. Here's an example:

$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([$sql_stmt, 'bind_param'], [$param_type, ...$params]);
mysqli_stmt_execute($sql_stmt);
Copy after login

The above is the detailed content of How to Resolve the 'mysqli_stmt::bind_param() Expected to be a Reference, Value Given' 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