Resolving "Cannot pass parameter 2 by reference" Error When Using bindParam with Constants
In your code snippet, you encounter the error "Cannot pass parameter 2 by reference" when attempting to use bindParam with a constant value (e.g., PDO::PARAM_NULL). This error occurs because bindParam requires a variable to bind to, while you are passing a constant value.
To resolve this issue, you need to use bindValue instead of bindParam. bindValue binds a value directly to the parameter, rather than a variable. Here's the corrected code:
try { $dbh = new PDO('mysql:dbname=' . DB . ';host=' . HOST, USER, PASS); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); } catch(PDOException $e) { ... } $stmt = $dbh->prepare('INSERT INTO table(v1, v2, ...) VALUES(:v1, :v2, ...)'); $stmt->bindValue(':v1', null, PDO::PARAM_INT); // Using bindValue with null and explicit type
Note: You may be tempted to use bindValue(':param', null, PDO::PARAM_NULL), but this approach does not always work. Instead, it is recommended to use the explicit type, such as PDO::PARAM_INT in this example.
The above is the detailed content of Why Does `bindParam` Fail with Constants and How Can I Use `bindValue` Instead?. For more information, please follow other related articles on the PHP Chinese website!