Reputation: 46479
I know this might be a very basic question, but I am new to php and databases, I'm trying to figure out a while condition that will keep while loop running until all (would be also nice to know how to do it for fixed amount) of data is taken form database.
$stmt = $db->prepare("SELECT * FROM icecreams");
$stmt -> execute();
$row = $stmt -> fetchAll(PDO::FETCH_ASSOC);
So now I need to figure out what while condition I need, the logic is
while (there is data to fetch) {
echo "<h1>$row['flavour']</h1>";
echo "...";
}
Upvotes: 1
Views: 1818
Reputation: 33
$stmt = $db->prepare("SELECT * FROM properties");
$stmt -> execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$row['column_name']
}
Upvotes: 1
Reputation: 20737
If you do this then you will see that you have all of your data in an array already:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>'.print_r($row, true).'</pre>';
So now you can simply loop the items an access the data:
foreach($row as $k=>$v)
{
echo $k.'<br>'; // this will show you what row # you are on, sometimes useful :)
echo $v['title'].'<br>';
// etc....
}
Upvotes: 0
Reputation: 76646
fetchAll()
returns an array containing all of the result set rows, whereas fetch()
returns a single row from the result-set.
fetchAll()
Usage:
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($array as $row) {
# code...
}
fetch()
Usage:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
# code...
}
If you're going to use this for printing HTML, the second option seems nicer. For small recordsets, the performance difference shouldn't really matter, but if you're working with a lot of records, then fetchAll()
might be a little slower, as it tries to map the entire data into a single array at once.
Upvotes: 3
Reputation: 482
fetchAll
does fetch everything as an associative array (as flag FETCH_ASSOC
tells). It does it automatically for, you don't have to worry about it.
Upvotes: 0