Home > Article > Backend Development > Why Does PDO\'s `bindParam` Fail with Constants, and How Can I Fix the \'Cannot pass parameter 2 by reference\' Error?
Troubleshooting "Cannot pass parameter 2 by reference" Error in PDO bindParam with Constants
While working with PDO, developers may encounter the puzzling error "Cannot pass parameter 2 by reference." This typically occurs when using bindParam with constant values.
To rectify this issue, it's crucial to switch from using bindParam to bindValue. bindParam takes a variable as a reference and only interpolates its value during statement execution. In contrast, bindValue immediately evaluates the provided value and incorporates it into the statement.
The following example demonstrates the correct usage of bindValue:
$stmt = $dbh->prepare('INSERT INTO table(v1, v2, ...) VALUES(:v1, :v2, ...)'); $stmt->bindValue(':v1', null, PDO::PARAM_INT);
Note that binding a constant value like null should be done using PDO::PARAM_INT or another appropriate PDO::PARAM type, rather than PDO::PARAM_NULL.
By following this simple adjustment, developers can effectively resolve the "Cannot pass parameter 2 by reference" error and proceed with their database operations without hindrance.
The above is the detailed content of Why Does PDO\'s `bindParam` Fail with Constants, and How Can I Fix the \'Cannot pass parameter 2 by reference\' Error?. For more information, please follow other related articles on the PHP Chinese website!