Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php PDO fetchAll() - while not working, foreach works

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" ?

like image 885
Mafitsi Avatar asked Jul 18 '13 16:07

Mafitsi


People also ask

What is the purpose of the PDOStatement fetchAll () function?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

What is the difference between fetch and fetchAll?

if you want all records .. for fetch you are going to need to loop like while($row = $stmt->fetch()) { # work with the record } for fetchAll() you have direct acces to the records as a array.

What does fetchAll do in PHP?

Definition and Usage The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.

What is the default data type for the fetchAll () result?

System-missing values are always converted to the Python data type None. By default, user-missing values are converted to the Python data type None.


1 Answers

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);

while ($row = $page->fetch(PDO::FETCH_ASSOC)){
   // do something awesome with row
} 

if you want to use a while and fetch all you can do

$rows = $page->fetchAll(PDO::FETCH_ASSOC);

// use array_shift to free up the memory associated with the record as we deal with it
while($row = array_shift($rows)){
   // do something awesome with row
}

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.

like image 90
Orangepill Avatar answered Nov 13 '22 22:11

Orangepill