I would like to know if i'm doing fine OR fetchAll() doesn't work with WHILE.
here is an exemple
$db=new PDO("mysql:host=" .$dbhost. "; dbname=" . $dbname, $dbuser, $dbpass);
$page=$db->prepare("SELECT * FROM page");
$page->execute();
foreach ($page->fetchAll(PDO::FETCH_ASSOC) as $row) {
//echo a row
//is working
}
however, i if try looping with a while
while ($row=$page->fetchAll(PDO::FETCH_ASSOC)){
//echo a row
//Show empty
}
i tryed to use only fetch(), it was working, my question: why fetchAll() doesn't work with "WHILE" ?
I tried to reproduce your case. Look here:
script.php
Database test
output
The output means, that while statement was executed once and prints all the rows, that the query should return, which is absolutely correct, because fetchAll returns an array of arrays with all the rows. PHP interprets it as true and while runs once.
While
foreach
will iterate over the array of arrays and you will have the corresponding row every time.Fetch all returns all of the records remaining in the result set. With this in mind your foreach is able to iterate over the result set as expected.
For the equivalent while implementation should use
$page->fetch(PDO::FETCH_ASSOC);
if you want to use a while and fetch all you can do
A word of warning though: fetch all will do exactly that, if the result size is large it will stress the resources on your machine. I would only do this if I know that the result set will be small, or I'm forcing that by applying a limit to the query.
no need to loop through the recordset, because
fetchAll
- well - fetches all the records in one command. Nice, isn't it?With
fetchAll
In while loop you have fetched all records in the first iteration and there is nothing to fetch the next time. Inforeach
also you have fetched all records in the first line, butforeach
uses the result for iteration.From the PHP Manual:
Since the method you're using returns an array,
while ($row=$page->fetchAll(PDO::FETCH_ASSOC))
is going to set $row to an array of the entire result set. What you're expecting is for the fetchAll method to extend the Iterator class, which it does not.A
foreach
is the right way to go here.