PDO - BindParam Fatal error: Cannot pass parameter 2 by reference - why?

Hello all,

If we have something like this, this will work, and we will not get any errors here:
I’m using something like this, and I’m able to insert data into the database.

Case A

$stmt = $this->_dbh->prepare("INSERT INTO ourTable (ourColumn) VALUES (?)");
 $stmt->bindParam(1, $someVo->getColumn(), PDO::PARAM_STR, 255);

If I do, however:
Case B

$stmt = $this->_dbh->prepare("SELECT d.ourColumn FROM ourTable d WHERE d.ourColumn LIKE ?");
$stmt->bindParam(1, '%' . $someVo->getColumn() . '%', PDO::PARAM_STR, 255);

I do get:

Fatal error: Cannot pass parameter 2 by reference

  • pointing to my bindParam line above.

I don’t understand what this error means. Neither what pass something by reference really means… can I have some lights here?
I’ve read here and there that this may be related to the fact that we CANNOT pass values with bindParam but, that’s what I do on the case A with success. :shifty:

Thanks in advance, again and again,

There is bindParam and bindValue. The method bindValue would work with what you are doing but bindParam errors because by using string concentration the reference to the original value is lost. You would need to assign the result of the string manipulation to a separate variable and bind that when using bindParam.


Ok. bindParam binds a variable to a given placeholder. That variable is not evaluated at that time, instead, it is bind by reference.

This means that, since it’s not evaluated at that time, we actually don’t have access to that variable value, so, we can’t concatenate nothing to it.

It’s bind by reference, so unless the reference is changed, we cannot modify it’s value, because we don’t have access to it, and we shouldn’t. Because, if we had, we will defeat the all propose of reference? (I’m still shacking here…).

So, we should first do:

$preparedVariable = '%'.$something->getSomething().'%';

And then bind that preparedVariable.

Because, by doing so, we are respecting the reference requirement of bindParam. We are referring (and NOT access the value) of a given variable.

If the above is precise:
Should we use bindValue or bindParam - probably this doesn’t matter here, and will only manner if we deal with stored procedures? (I don’t wish to disguise: I’m absolutely unaware of what stored procedures are, but that’s not the point here, I’ve just read that on php manual).

Thanks a lot,