"bindParam in a loop eats your data" shock

Well, there’s a couple of hours of my life I won’t get back.

So it suddenly seemed like a good idea to abstract the construction of PDO queries into a base class (since I had it anyway) and do a lot less typing. And it all works brilliantly, except as it iterates through the $data hash I’m giving it, somehow the last value gets used for all the columns I’m updating. Something wrong somewhere. So I check everything.

[php]
$query = $conn->prepare($queryString);
foreach ($data as $key => $value) {
$query->bindParam(‘:’ . $key, $value);
}
[/php]

Every.

Damn.

Thing.

So two hours later, still no idea why it’s happening. Until I finally trawl StackOverflow and find the

(http://stackoverflow.com/questions/146897/error-with-bindparam-overwriting-in-php) – which is that bindParam binds by reference to a variable, not by value. So the last $value used is the one evaluated for all of them. Completely by design. You use bindValue instead, of course.

[php]
$query = $conn->prepare($queryString);
foreach ($data as $key => $value) {
$query->bindValue(‘:’ . $key, $value);
}
[/php]

And the worst thing is I knew this already, and had forgotten. That happens a lot these days…

Advertisements