Home >Backend Development >PHP Tutorial >Why Does mysqli_stmt::bind_param() Throw 'Parameter ... expected to be a reference, value given'?

Why Does mysqli_stmt::bind_param() Throw 'Parameter ... expected to be a reference, value given'?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 09:11:15664browse

Why Does mysqli_stmt::bind_param() Throw

mysqli bind_param() Error: Passing Values Instead of References

The error "Parameter 3 to mysqli_stmt::bind_param() expected to be a reference, value given" arises when mysqli_stmt::bind_param() is passed an array of values instead of an array of references to those values.

PDO Code

In the PDO code provided:

$params = array(1,"2","3","4");

The $params array contains values rather than references to those values. To fix this, use & to create references:

$params = array(1,&"2", &"3", &"4");

OOP Code

Similarly, in the OOP code:

array_unshift($params, $param_type);

This line prepends the $param_type string to the beginning of the $params array, but it does not create references to the parameter values. To create references, use the & character:

array_unshift($params, $param_type);
foreach ($params as $key => $value) {
    $params[$key] =& $value;
}

Alternative Solution Using Spread Operator (PHP 5.6 )

In PHP versions 5.6 and above, you can use the spread operator (...) to pass the $params array as individual arguments without having to manually create references:

mysqli_stmt_bind_param($sql_stmt, $param_type, ...$params);

$insert_stmt->bind_param($param_type, ...$params);

By passing references or using the spread operator, you can ensure that mysqli_stmt::bind_param() receives an array of references to the parameter values, resolving the error.

The above is the detailed content of Why Does mysqli_stmt::bind_param() Throw 'Parameter ... expected to be a reference, value given'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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