Home >Backend Development >PHP Tutorial >Why Does My PHP Code Throw a 'Cannot Pass Parameter 2 by Reference' Error?

Why Does My PHP Code Throw a 'Cannot Pass Parameter 2 by Reference' Error?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 16:28:11420browse

Why Does My PHP Code Throw a

Understanding PHP's "Cannot Pass Parameter 2 by Reference" Error

In PHP, passing parameters by reference allows changes made to the passed variable to be reflected in the original variable. However, if a parameter is expected to be passed by reference but it's not, it can result in the "Cannot pass parameter 2 by reference" error.

Specific Error Scenario: UPDATE Query with Date Comparison

Consider the following PHP code:

$selectedDate = date('d-m-Y', ($createDate));

$sql = "UPDATE Session SET Active = ? WHERE DATE_FORMAT(SessionDate,'%Y-%m-%d' ) <= ?";
$update = $mysqli->prepare($sql);
$update->bind_param("is", 0, $selectedDate);  // Line 13

In this example, Line 13 attempts to bind two parameters to the prepared statement:

  • The first parameter is an integer (0) and is passed by value.
  • The second parameter is a string ($selectedDate) and is also passed by value.

However, the second parameter is expected to be a reference to a variable, indicated by the "s" in the "is" type string. Since it's not passed by reference, the error "Cannot pass parameter 2 by reference" is thrown.

Resolution: Passing a Variable Reference

To resolve this error, pass a variable reference to the second parameter, as shown below:

$isActive = 0;
$update->bind_param("is", $isActive, $selectedDate);

By passing $isActive by reference, changes made to it within the prepared statement will be reflected in the original variable.

Understanding References in PHP

For more information on references in PHP, you can refer to the following documentation: http://php.net/manual/en/language.references.pass.php.

The above is the detailed content of Why Does My PHP Code Throw a 'Cannot Pass Parameter 2 by Reference' Error?. 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