[thelist] php/mysql/html - best way to loop data

Peter Lowe pgl at instinct.org
Mon Aug 4 15:20:32 CDT 2003


On Aug 04, Tom Dell'Aringa wrote:
> --- Peter Lowe <pgl at instinct.org> wrote:
> > Here's how I would do it:
> > 
> > <? while ($listing = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
> > 
> > <tr>
> > <td><?=$listing['title']?></td>
> > <td><?=$listing['category']?></td>
> > <td><?=$listing['actor_1']?></td>
> > <td><?=$listing['actor_2']?></td>
> > <td><img src="images/<?=$listing['rating']?>_star.gif"></td>
> > </tr>
> > 
> > <? } ?>
> 
> This is a really nice way to loop through a result set. Is there a
> "best practice" for this? I have been using the mysql_fetch_array()
> but not quite like this. Just curious.
> 
> Tom

Thanks. What do you mean by "best practice" though, sorry?

BTW, I don't normally use mysql_fetch_array() much in the main part of a
page. I used to but kept having to format variables before output. eg:

<?
while ($listing = mysql_fetch_array($result, MYSQL_ASSOC)) {
	if ($listing['actor_1'] && !$listing['actor_2']) {
		$listing['one_man_show'] = true;
		$loners[] = $listing['actor_1'];
		}

	if (strlen($listing['title']) > 45)
		$listing['title'] = substr($listing['title'], 0, 45) .  '...';
?>

<tr>
<td<?=($listing['one_man_show'] ? ' style="font-weight: bold;"' : '')?>><?=$listing['title']?></td>
</tr>

<?	} ?>

Not the best example off the top of my head (I can think of a few ways
to neaten it up... but... must... resist...) but I hope you can see what
I mean. Now I normally write a function that loops through the result
set and returns an array of ready to print values. eg:

<?
function get_listings() {
	$sql	= 'select * from listings';
	$result	= mysql_query($sql);

	while ($listing = mysql_fetch_array($result, MYSQL_ASSOC)) {
		// ... twiddly bits here...

		$listings[$listing['id']] = $listing;
		}

	return $listings ? $listings : array();
	}
?>

Stick that in an include file at the top of your page and everything's
nice and neat. It also gets rid of any unecessary variables lying
around, cos you can use the function directly with a foreach() loop:

<? foreach (get_listings() as $listingid => $listing) { ?>

<tr>
<td><?=$listing['title']?></td>
</tr>

<?	} ?>

Looping through results like this kind of offends the efficient part of
my brain -- building that big array just to loop through it again
doesn't seem right -- but I think it's worth it.

cheers,

Peter

-- 
The Czech Republic: Home of the world's finest beer.
Litres drunk by Czechs so far this year: 970,296,881.08

 - http://prague.tv/toys/beer/


More information about the thelist mailing list