pdo prepared statement multiple execution?

2019-07-31 21:06发布

问题:

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

回答1:

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
    }
}

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.

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
    }
}

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.

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.



回答2:

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.