pdo准备的语句多次执行? [英] pdo prepared statement multiple execution?

查看:99
本文介绍了pdo准备的语句多次执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是要在自己的站点中实现PDO,但我想知道是否可以多次执行准备好的语句?

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()){

然后我将使用while循环对此SQL

and then I would use a while loop for this SQL

我可以在while循环中使用相同的$ 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

推荐答案

是的,您可以重用相同的准备好的语句,但是不能在问题中使用它.您要尝试执行的操作与执行此操作基本相同:

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:

for ($i=0; $i<$some_number; $i++) {
    echo $i."\n";
    for ($i=0; $i<$some_number; $i++) {
        // do something
    }
}

第二个for循环将移动与原始指针相同的指针,因此上面的输出将只是"0",表明原始的for循环只发生了一次.

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 original for loop only happened once.

因此,为了解决这个问题,您需要将第一个execute的结果存储到数组中,然后对其进行迭代.这样,您就不必担心任何指针

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 pointers

$SQL = $dbh->prepare("SELECT * FROM user WHERE id=? AND users=?");
$SQL->execute(array($id,$userid));
$checks = $SQL->fetchAll();
foreach ($checks as $check) {
    $SQL->execute(array($id2,$userid2));
    while ($check2 = $SQL->fetchObject(){
        //while loops for second execution
    }
}

这样,您使用的是完全相同的预处理语句(这很好),并且原始的$check变量可用于while循环中.

This way, you are using exactly the same prepared statement (which is good) and the original $check variable is available to be used in the while loop.

但是,尽管如此,我很直觉,您可以将所有内容放入一个SQL查询中,而无需像这样循环遍历它.

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.

这篇关于pdo准备的语句多次执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆