在循环内绑定PDO语句的参数

Bud*_*ddy 25 php foreach pdo prepared-statement

我试图在循环中绑定SQL查询的参数:

$db = new PDO('mysql:dbname=test;host=localhost', 'test', '');  
$stmt = $db->prepare('INSERT INTO entries VALUES (NULL, ?, ?, ?, NULL)');

$title = 'some titile';
$post = 'some text';
$date = '2010-whatever';  

$reindex = array(1 => $title, $post, $date); // indexed with 1 for bindParam

foreach ($reindex as $key => $value) {  
    $stmt->bindParam($key, $value);  
    echo "$key</br>$value</br>";  //will output: 1</br>some titile</br>2</br>some text</br>3</br>2010-whatever</br>
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在所有3个字段的数据库中插入2010-whatever.

这个工作正常:

$stmt->bindParam(1, $title);
$stmt->bindParam(2, $post);
$stmt->bindParam(3, $date);
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是为什么foreach循环中的代码失败并在字段中插入错误的数据?

lon*_*day 46

问题是bindParam需要参考.它将变量绑定到语句,而不是值.由于foreach循环中的变量在每次迭代结束时未设置,因此您无法使用问题中的代码.

您可以使用以下参考执行以下操作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
}
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做,使用bindValue:

foreach ($reindex as $key => $value) {
    $stmt->bindValue($key, $value);  // bind the value to the statement
}
Run Code Online (Sandbox Code Playgroud)