PHP PDO bindParam was falling in a foreach

前端 未结 3 1177
旧时难觅i
旧时难觅i 2020-12-05 03:15

I had a loop like that :

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

Nothing c

相关标签:
3条回答
  • 2020-12-05 03:26

    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);
    }
    
    0 讨论(0)
  • 2020-12-05 03:42

    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);
    }
    ?>
    
    0 讨论(0)
  • 2020-12-05 03:44

    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]);
    }
    
    0 讨论(0)
提交回复
热议问题