PDO pass by reference notice?


$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$stmt->bindParam(':color', $someClass->getColor());

yields this:

Runtime notice
Only variables should be passed by

though it still executes.


$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = $someClass->getColor();

runs without complaint.

I don’t understand the difference?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The description of PDOStatement::bindParam() states that it binds a PHP variable to a quesitonmark or named placeholder. Since you are trying to pass a class’s method (even though that method does return a value) it is still not a variable name, hence the warning. You might want to look at PDOStatement::bindValue() to future-proof your code.

Solution 2

The second parameter of bindParam is a variable reference. Since a function return cannot be referenced, it fails to strictly meet the needs of the bindParam parameter (PHP will work with you though and will only issue a warning here).

To get a better idea, here’s and example: this code will produce the same results as your second example:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = NULL; // assigned here
$tempColor = $someClass->getColor(); // but reassigned here

That won’t be possible with a function return.

Solution 3

If you want to avoid assigning the value to a variable, you might be better off trying:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = ?");

As others have mentioned, the error is caused because PDO::statement->bindParam expects param 2 to be a variable passed by reference.

Solution 4

If you really want to bind a value instead of a reference, you can use the PDOStatement::bindValue and then you code would look something like this:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$stmt->bindValue('color', $someObject->getColor());

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply