Bricktop Posted October 30, 2008 Share Posted October 30, 2008 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 More sharing options...
o3d Posted October 30, 2008 Share Posted October 30, 2008 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']; } Link to comment https://forums.phpfreaks.com/topic/130728-solved-easy-question-output-by-group/#findComment-678478 Share on other sites More sharing options...
Bricktop Posted October 30, 2008 Author Share Posted October 30, 2008 Brialliant! Worked a treat! Thanks o3d! Link to comment https://forums.phpfreaks.com/topic/130728-solved-easy-question-output-by-group/#findComment-678491 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.