Home >Backend Development >PHP Tutorial >How to Fix the 'mysqli_stmt::bind_param() Expected a Reference' Error?
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; }
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);
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();
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!