I had a loop like that :
foreach($Fields as $Name => $Value){
$Query->bindParam(\':\'.$Name, $Value, PDO::PARAM_STR);
}
Nothing c
If you don't need the ability to keep the variable in sync with the bound parameter before the query is executed (which is the case 99.9% of the time, in my experience), it's probably better to simply use PDOStatement::bindValue() instead of PDOStatement::bindParam():
foreach ($Fields as $Name => $Value) {
$Query->bindValue(':' . $Name, $Value, PDO::PARAM_STR);
}
However, thanks to this guys. I found out that you need to pass the value by reference with a &
before like that :
foreach($Fields as $Name => &$Value){
$Query->bindParam(':'.$Name, $Value, PDO::PARAM_STR);
}
This was driving me nuts.
Actual quote from PHP.net :
Vili 28-May-2010 12:01
This works ($val by reference):
<?php
foreach ($params as $key => &$val){
$sth->bindParam($key, $val);
}
?>
This will fail ($val by value, because bindParam needs &$variable):
<?php
foreach ($params as $key => $val) {
$sth->bindParam($key, $val);
}
?>
There is one more nasty option to get rid of this issue.
You can simply iterate through the array keys, and get each value as a parameter by using these keys:
foreach(array_keys($params) as $key) {
$sth->bindParam($key, $params[$key]);
}