This is a part of
PHP & MySQL Novice to Ninja, 5th Edition by Kevin Yank
Normally when we perform a SELECT query , we use the condition of a
while loop or a foreach loop to retrieve each row of the results, one
at a time:
while ($row = $result->fetch()) foreach ($result as $row)
When we process the result of a query this way, PHP actually retrieves
each row from the database as the loop requests it, and throws it away
when it moves on to the next row . This saves PHP from having to use a
lot of memory to hold onto all the rows of results at once.Most of
the time, we developers have no need to know that PHP is taking this
clever shortcut. But every once in a while, we’ll want to send another
SQL query to the MySQL server before we’ve worked through all the
results of the previous query .That’ s exactly what’ s about to
happen in this code if we aren’t careful: we’ve just run a SELECT
query to ask for a list of all jokes belonging to a particular author,
and as we work through that list, we’d like to perform a DELETE query
for each one. The problem is, as far as MySQL knows, it will still be
busy sending us the results of the SELECT query; we can’t just
interrupt it and ask for it to start running DELETEs! Doing so would
cause our DELETEs to fail with an error .That’ s where the fetchAll
method comes in. By calling this method on our prepared statement
($s), we ask PHP to retrieve the entire set of results for the query
and store them in a PHP array ($result):
My question is Why I can execute MYSQL statements while I have one or more PDOStatement result sets being used in my PHP code?
even I can delete all rows being referenced in those result sets
<?php
include_once $_SERVER["DOCUMENT_ROOT"] . '/DBconnection.inc.php';
$pds1 = $dbi->query("SELECT name FROM tbl1");
$row = $pds1->fetch();
var_dump($row['name']);
$pds2 = $dbi->query("SELECT user FROM tbl2");
$row = $pds2->fetch();
var_dump($row['user']);
$row = $pds1->fetch();
var_dump($row['name']);
$row = $pds2->fetch();
var_dump($row['user']);
$pds3= $dbi->prepare("DELETE FROM tbl1;");
$pds3->execute();
$row = $pds1->fetch();
var_dump($row['name']);
$row = $pds2->fetch();
var_dump($row['user']);
?>
This is an area where the behavior of PDO is going to depend on the database you’re using and the PDO driver implementation. You might be able to execute new queries while you’re still fetching the results of a select statement, or you might not.
In general, the safest and most compatible way to use PDO connections is:
$pds1->closeCursor())