PHP PDO bindParam was falling in a foreach
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);
}
?>
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);
}