在循环内绑定 PDO 语句的参数
我正在尝试在循环内绑定 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>
}
上面的代码在数据库中的所有 3 个字段 2010-whatever
中插入。
这个工作正常:
$stmt->bindParam(1, $title);
$stmt->bindParam(2, $post);
$stmt->bindParam(3, $date);
那么,我的问题是为什么 foreach 循环中的代码失败并在字段中插入错误的数据?
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>
}
The code above inserts in database in all 3 fields 2010-whatever
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
bindParam
需要引用。它将变量绑定到语句,而不是值。由于foreach
循环中的变量在每次迭代结束时都未设置,因此您无法使用问题中的代码。您可以使用
foreach
中的引用执行以下操作:或者您可以使用
bindValue
执行此操作:The problem is that
bindParam
requires a reference. It binds the variable to the statement, not the value. Since the variable in aforeach
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
:Or you could do this, using
bindValue
: