循环内 PDO 语句的绑定参数
我正在尝试在循环内绑定 SQL 查询的参数:
I'm trying to bind parametres for SQL query inside a loop:
$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>
}
以上代码在所有 3 个字段中插入数据库2010-whatever
.
The code above inserts in database in all 3 fields 2010-whatever
.
这个很好用:
$stmt->bindParam(1, $title);
$stmt->bindParam(2, $post);
$stmt->bindParam(3, $date);
那么,我的问题是为什么 foreach 循环中的代码会失败并在字段中插入错误的数据?
So, my question is why the code in the foreach-loop fails and inserts wrong data in the fields?
推荐答案
问题在于 bindParam
需要引用.它将变量绑定到语句,而不是值.由于 foreach
循环中的变量在每次迭代结束时都未设置,因此您不能使用问题中的代码.
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.
您可以使用 foreach
中的引用执行以下操作:
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
}
或者你可以这样做,使用 bindValue
:
Or you could do this, using bindValue
:
foreach ($reindex as $key => $value) {
$stmt->bindValue($key, $value); // bind the value to the statement
}
相关文章