循环内 PDO 语句的绑定参数
问题描述
我正在尝试在循环内绑定 SQL 查询的参数:
I'm trying to bind parametres for SQL query inside a loop:
以上代码在所有 3 个字段中插入数据库2010-whatever
.
The code above inserts in database in all 3 fields 2010-whatever
.
这个很好用:
那么,我的问题是为什么 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
:
或者你可以这样做,使用 bindValue
:
Or you could do this, using bindValue
:
这篇关于循环内 PDO 语句的绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!