I'm trying to bind parametres for SQL query inside a loop:
我试图在循环中绑定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>
}
The code above inserts in database in all 3 fields 2010-whatever
.
上面的代码插入数据库中的所有3个字段2010-无论如何。
This one works fine:
这个工作正常:
$stmt->bindParam(1, $title);
$stmt->bindParam(2, $post);
$stmt->bindParam(3, $date);
So, my question is why the code in the foreach-loop fails and inserts wrong data in the fields?
所以,我的问题是为什么foreach循环中的代码失败并在字段中插入错误的数据?
1 个解决方案
#1
45
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.
问题是bindParam需要引用。它将变量绑定到语句,而不是值。由于foreach循环中的变量在每次迭代结束时未设置,因此您无法使用问题中的代码。
You can do the following, using a reference in the 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
}
Or you could do this, using bindValue
:
或者您可以使用bindValue执行此操作:
foreach ($reindex as $key => $value) {
$stmt->bindValue($key, $value); // bind the value to the statement
}
#1
45
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.
问题是bindParam需要引用。它将变量绑定到语句,而不是值。由于foreach循环中的变量在每次迭代结束时未设置,因此您无法使用问题中的代码。
You can do the following, using a reference in the 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
}
Or you could do this, using bindValue
:
或者您可以使用bindValue执行此操作:
foreach ($reindex as $key => $value) {
$stmt->bindValue($key, $value); // bind the value to the statement
}