pdo准备好的语句多次执行?
我刚刚在我的网站中实现 PDO,但我想知道是否可以多次执行准备好的语句?
$SQL = $dbh->prepare("SELECT * FROM user WHERE id=? AND users=?");
$SQL -> execute(array($id,$userid));
while($check = $SQL -> fetchObject()){
然后我会对此 SQL 使用 while 循环
我可以在 while 循环中使用相同的 $SQL 进行另一个执行吗?这样我就不必再次输入准备好的语句了?
$SQL -> execute(array($id2,$userid2));
while($check2 = $SQL ->fetchObject(){
//while loops for second execution, but I'm not sure how it works cause
//its using the same $SQL?
}
}//this end bracket is for the first while loop
I'm just getting to implement PDO in my site but I was wondering if it is possible to execute prepared statement multiple times?
$SQL = $dbh->prepare("SELECT * FROM user WHERE id=? AND users=?");
$SQL -> execute(array($id,$userid));
while($check = $SQL -> fetchObject()){
and then I would use a while loop for this SQL
Can I use the same $SQL for another execution within the while loop? So I don't have to type in the prepared statement again?
$SQL -> execute(array($id2,$userid2));
while($check2 = $SQL ->fetchObject(){
//while loops for second execution, but I'm not sure how it works cause
//its using the same $SQL?
}
}//this end bracket is for the first while loop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以重复使用相同的准备好的语句,但不能重复使用它在问题中的方式。您想要做的事情本质上与执行此操作相同:
第二个
for
循环移动与原始指针相同的指针,因此上面的输出将只是“0
”表明原来的for
循环只发生了一次。因此,为了解决这个问题,您需要将第一次执行的结果存储到一个数组中,然后对其进行迭代。这样您就不必担心任何指针
这样,您将使用完全相同的准备好的语句(这很好),并且原始的
$check
变量可在中使用> while 循环。
然而,尽管如此,我有一种强烈的预感,您可能可以将所有内容放入一个 SQL 查询中,而不需要像这样循环它。
Yes, you can reuse the same prepared statement, but not how you have it in the question. What you are trying to do is essentially the same as doing this:
The the second
for
loop moves the same pointer as the original one, so therefore the output from the above would simply be "0
" indicating that the originalfor
loop only happened once.So in order to get around this, you will need to store the results of the first
execute
into an array and then iterate over it. That way you won't have to worry about any pointersThis way, you are using exactly the same prepared statement (which is good) and the original
$check
variable is available to be used in thewhile
loop.However, with all that said, I have a strong hunch that you can probably get everything into one single SQL query without the need for looping over it like this.
是的,这是可能的。准备一次,根据需要执行多次。
当然,我不确定为什么你要在循环中执行
SELECT
...这通常没有多大意义。Yes, it is possible. Prepare once, execute as many times as you need to.
Of course, I'm not sure why you're doing a
SELECT
in a loop... that typically doesn't make much sense.