Home > Backend Development > PHP Tutorial > How to Solve the 'Expected to be a Reference' Error in mysqli bind_param()?

How to Solve the 'Expected to be a Reference' Error in mysqli bind_param()?

Susan Sarandon
Release: 2024-12-13 10:57:15
Original
170 people have browsed it

How to Solve the

Handling "Expected to be a Reference" Error in mysqli bind_param()

The error message "Parameter 3 to mysqli_stmt::bind_param() expected to be a reference, value given" arises when binding a value to a prepared statement. To resolve this issue, the value provided must be a reference to an actual variable rather than the value itself.

In the provided code snippet, the $params array contains values that are not references. To bind the values correctly, you can use the following approach:

$query = "INSERT INTO test (id,row1,row2,row3) VALUES (?,?,?,?)";
$param_type = "isss";

// PHP 7+
$sql_stmt = mysqli_prepare($mysqli, $query);
mysqli_stmt_bind_param($sql_stmt, $param_type, ...$params);

// PHP 5.6 - 7.0
$sql_stmt = mysqli_prepare($mysqli, $query);
$arr = array($sql_stmt, $param_type);
foreach ($params as $param) {
    $arr[] = &$param;
}
call_user_func_array('mysqli_stmt_bind_param', $arr);

mysqli_stmt_execute($sql_stmt);
Copy after login

Usage of References

In PHP 5.3 and below, references are not required for binding values to a prepared statement. However, starting from PHP 5.4, references are mandatory. The reason for this change is to prevent unwanted variable copying and potential memory leaks.

By using references, the binding process becomes more efficient as the bound values are directly modified, eliminating the need for extra variable assignments.

Conclusion

Remember that when using mysqli bind_param() with values that are not references, you need to pass them as references or use alternative approaches to bind values properly. This ensures efficient and error-free execution of your SQL queries.

The above is the detailed content of How to Solve the 'Expected to be a Reference' Error in mysqli bind_param()?. 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