Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value? Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value? mysql mysql

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?


You need to use bindValue, not bindParam

bindParam takes a variable by reference, and doesn't pull in a value at the time of calling bindParam. I found this in a comment on the PHP docs:

bindValue(':param', null, PDO::PARAM_INT);

P.S. You may be tempted to do this bindValue(':param', null, PDO::PARAM_NULL); but it did not work for everybody (thank you Will Shaver for reporting.)


When using bindParam() you must pass in a variable, not a constant. So before that line you need to create a variable and set it to null

$myNull = null;$stmt->bindParam(':v1', $myNull, PDO::PARAM_NULL);

You would get the same error message if you tried:

$stmt->bindParam(':v1', 5, PDO::PARAM_NULL);


When using INTEGER columns (that can be NULL) in MySQL, PDO has some (to me) unexpected behaviour.

If you use $stmt->execute(Array), you have to specify the literal NULL and cannot give NULL by variable reference.So this won't work:

// $val is sometimes null, but sometimes an integer$stmt->execute(array(    ':param' => $val));// will cause the error 'incorrect integer value' when $val == null

But this will work:

// $val again is sometimes null, but sometimes an integer$stmt->execute(array(    ':param' => isset($val) ? $val : null));// no errors, inserts NULL when $val == null, inserts the integer otherwise

Tried this on MySQL 5.5.15 with PHP 5.4.1