Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO bindParam was falling in a foreach

Tags:

php

pdo

I had a loop like that :

foreach($Fields as $Name => $Value){     $Query->bindParam(':'.$Name, $Value, PDO::PARAM_STR); } 

Nothing complicated. However, each value was set to the last one in the array ($Fields).

How can I fix that ?

like image 330
David Bélanger Avatar asked Aug 27 '12 15:08

David Bélanger


1 Answers

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); } ?> 
like image 146
David Bélanger Avatar answered Sep 22 '22 03:09

David Bélanger