bindParam Error with Constant Values in PDO
When attempting to use bindParam with a constant value, such as PDO::PARAM_NULL, developers may encounter the error "Cannot pass parameter 2 by reference."
Code Snippet with the Error
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->bindParam(':v1', PDO::PARAM_NULL); // --> Here's the problem
Solution
The error occurs because bindParam takes a variable by reference and doesn't retrieve a value when called. The correct method for binding a constant value is bindValue.
Corrected Code
$stmt->bindValue(':v1', null, PDO::PARAM_INT);
Note:
Avoid using bindValue(':param', null, PDO::PARAM_NULL), as it may not be reliable.
The above is the detailed content of Why Does `bindParam` Fail with Constant Values in PDO?. For more information, please follow other related articles on the PHP Chinese website!