Binding params for PDO statement inside a loop

前端 未结 1 1034
名媛妹妹
名媛妹妹 2020-11-28 10:05

I\'m trying to bind parametres for SQL query inside a loop:

$db = new PDO(\'mysql:dbname=test;host=localhost\', \'test\', \'\');  
$stmt = $db->prepare(         


        
相关标签:
1条回答
  • 2020-11-28 10:32

    The problem is that bindParam requires a reference. It binds the variable to the statement, not the value. Since the variable in a foreach loop is unset at the end of each iteration, you can't use the code in the question.

    You can do the following, using a reference in the foreach:

    foreach ($reindex as $key => &$value) {  //pass $value as a reference to the array item
        $stmt->bindParam($key, $value);  // bind the variable to the statement
    }
    

    Or you could do this, using bindValue:

    foreach ($reindex as $key => $value) {
        $stmt->bindValue($key, $value);  // bind the value to the statement
    }
    
    0 讨论(0)
提交回复
热议问题