Jump to content

[SOLVED] Easy Question - output by group


Bricktop

Recommended Posts

Me again!

 

Not sure what's wrong with me today - just keep forgetting basic code syntax!

 

Anyway, I have a script which outputs news items under categories.  For example, we have "Headlines", "Technology" and "Sport".  The news items stored under each of these categories are then displayed.  However, I can't remember how to use a single piece of code to achieve this, at the moment I'm doing:

 

$sql = mysql_query("SELECT * FROM news WHERE category = 'Headlines' ORDER BY id DESC");

echo '<strong>Headlines</strong>';
while ($a=mysql_fetch_array($sql))
{
extract($a);
echo ''.$newsitem.'';
}

$sql = mysql_query("SELECT * FROM news WHERE category = 'Technology' ORDER BY id DESC");

echo '<strong>Technology</strong>';
while ($a=mysql_fetch_array($sql))
{
extract($a);
echo ''.$newsitem.'';
}

$sql = mysql_query("SELECT * FROM news WHERE category = 'Sport' ORDER BY id DESC");

echo '<strong>Sport</strong>';
while ($a=mysql_fetch_array($sql))
{
extract($a);
echo ''.$newsitem.'';
}

 

I know the above is not the right way to go about this, could anyone enlighten me?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/130728-solved-easy-question-output-by-group/
Share on other sites

i assume this would do. this has not been tested, but should give you an idea of what to do...

 

$sql = mysql_query("SELECT category, col1, col2... FROM news ORDER BY category, id DESC");
$oldcat = '';
while ($a=mysql_fetch_array($sql)) {
if ($oldcat != $a['category']) {
	echo '<strong>'.$a['category'].'</strong><br>';
}
echo $a['col1'].' - '.$a['col2'].'<br>';
$oldcat = $a['category'];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.