PDO binds n times same value with foreach

后端 未结 3 1148
無奈伤痛
無奈伤痛 2021-01-25 06:15

I have function in PHP, which should bind in MySQL IN statement so many variables, that is in array. My problem is that variable and key is changing but function bind only last

相关标签:
3条回答
  • 2021-01-25 06:51

    The problem is that BindParam Passes the second value by reference. PHP reuses (or appears to in this case) the address of the $param, and not the actual value. Your foreach could have used:

    $stmt->bindParam($key, $data_array[$key]);
    

    This has the effect of binding the address location of the array at that key location, so when your sql executes, it gets the right value.

    You probably wanted:

    $stmt->bindValue($key, $param);
    

    which should evaluate in the foreach loop instead of at the execute statement, and is a passed value instead of an address location.

    0 讨论(0)
  • 2021-01-25 06:59

    If you pass the variable as reference it would work fine for value, but won't work for key.

    Example:

    foreach ($data_array as $key => &$param) {
        $key_number = $key + 1; //this won't work
        $key_name   = 'key' . $key_number;
        $stmt->bindParam($key_name, $param, PDO::PARAM_INT);
        var_dump($key_name);    // var dump 2
        var_dump($param);       // var dump 3
    }
    
    0 讨论(0)
  • 2021-01-25 07:14

    There is the difference between PDO::bindParam() and PDO::bindValue(). PDO::bindParam binds reference, not value. When foreach process ends, $param will reference to the last array value. In the time of execute call all binded references will be evaluated to same value.

    Official PDO::bindParam documentation says:

    Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

    If you want bind values in foreach use PDO::bindValue.

    0 讨论(0)
提交回复
热议问题