Home > Article > Backend Development > Why Does `bindParam` Fail with Constants in PDO and How to Fix It?
Passing Constants to bindParam: Error and Resolution
In PDO, the bindParam method allows binding variables to statement parameters by reference. However, when attempting to bind constant values such as PDO::PARAM_NULL, the error "Cannot pass parameter 2 by reference" may occur.
Cause of the Error:
bindParam requires a variable as the second argument, which it will bind to the parameter by reference. Attempting to pass a constant value directly will trigger the error since constants cannot be passed by reference.
Solution:
To bind constant values to statement parameters, use the bindValue method instead. bindValue binds variables by value, meaning it copies the value at the time of calling the method rather than creating a reference.
Modified Code:
$stmt->bindValue(':v1', null, PDO::PARAM_NULL);
By using bindValue, you can correctly bind constant values to statement parameters without encountering the "Cannot pass parameter 2 by reference" error. Remember to use PDO::PARAM_NULL for null values, not PDO::PARAM_INT or ''.
The above is the detailed content of Why Does `bindParam` Fail with Constants in PDO and How to Fix It?. For more information, please follow other related articles on the PHP Chinese website!