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);
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);
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!