Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

database results into an array then print

Status
Not open for further replies.

tyutghf

Technical User
Apr 12, 2008
258
0
0
GB
I have always looped through a database to display the results as in

Code:
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) : ?>
<tr>    
<td><?php echo $row['id'];?></td>

I have been reading up on some new php tutorials and they all seem to output to an array then print the array

Code:
$stmt = $db->prepare($query);
$stmt->execute();

$rows = $stmt->fetchAll();

<?php foreach($rows as $row): ?>
<td><?php echo $row['id']; ?></td>
<?php endforeach; ?>

None of the tutorials state why they are choosing to use this method. I guess it is for speed but will it be faster whe you fetch back many records?
 
Its more of how the PDO function your choose works rather than a performance consideration.

fetchAll returns an array with all the rows. So you work with the returned array.

You could also just call fetch() and still use a while loop with it.

I think it just comes down to what you want to do with the data. If you are going to process each row additionally for some reason, you may want to have them all in an array you can modify, so you can then have it ready with whichever values you altered when you want to output it to screen.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
the second is using an abstraction layer. there is no _requirement_ to load the recordset into an array. just convenience. in low/limited memory applications it is to be avoided.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top