Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using this code and I'm beyond frustration:

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 

PDO::PARAM_NULL, null, '', all of them fail and throw this error:

Fatal error: Cannot pass parameter 2 by reference in /opt/...

like image 750
Nacho Avatar asked Sep 08 '09 03:09

Nacho


2 Answers

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.)

like image 87
JasonWoof Avatar answered Oct 07 '22 16:10

JasonWoof


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); 
like image 42
Joe Phillips Avatar answered Oct 07 '22 16:10

Joe Phillips