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
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
forloop moves the same pointer as the original one, so therefore the output from the above would simply be “0” indicating that the originalforloop only happened once.So in order to get around this, you will need to store the results of the first
executeinto 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
$checkvariable is available to be used in thewhileloop.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.