I am wondering -- if this code:
// example 1
$statement = $pdo->query('SELECT * FROM table'); // MySQL
while ($row = $statement->fetch())
{
// doing something interesting
}
is equivalent of this code:
// example 2
$statement = $pdo->query('SELECT * FROM table'); // MySQL
foreach ($statement as $row)
{
// doing something interesting
}
in context of unbuffered queries in MySQL? (I am aware the loops give the same results.)
Or in other words:
- I'm sure, that executing the first example doesn't leave any data unread (according to the answer for Causes of MySQL error 2014 Cannot execute queries while other unbuffered queries are active) and I don't have to bother if a next
query
orprepare
right after the loop throwsGeneral error: 2014 Cannot execute queries while other unbuffered queries are active.
- I'm not sure if the second example works in the same way: that all data is fetched.
I tried something like that:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$statement = $pdo->query('SELECT * FROM table WHERE x = 1');
while(...) OR foreach(...)
{
// some magic
}
OR
$statement->fetch(); // just fetch(), not fetchAll()
$statement = $pdo->query('SELECT * FROM table WHERE x = 2'); // MySQL
...
And:
- In case of
while
orforeach
the code runs without errors. - In case of just
fetch()
, I, as supposed, geterror: 2014
.
So it seems, that I answered my own question;) But I'm still not sure. I couldn't find any docs or an SO question that would answer my problem, either.