I’m a bit stuck trying to get my code to output correctly, see below. It all works ok, but rather than displaying all news items, it only shows one for each month. What I need to do is group all news for a selected month with the month/year heading for that month. Hope this makes sense.
Any help greatly appreciated.
SS
$theQuery="Select * from isnews WHERE active = '1' GROUP BY YEAR(date) DESC, MONTH(date) ORDER BY YEAR(date) DESC, MONTH(date) DESC";
$newsQuery=mysql_query($theQuery);
if(mysql_num_rows($newsQuery)>0) {
while ($newsResult=mysql_fetch_array($newsQuery)) {
$newDate = $newsResult['date'] ;
echo '<div class="date">' . date('F Y ',strtotime($newDate)) . '</div>';
echo '<ul class="press">';
echo '<li>
<img src="'.$wwwUrl.'images/news/'.$newsResult['image'].'" width="'.$newsResult['tnWidth'].'" height="'.$newsResult['tnHeight'].'" title="'.$newsResult['title'].'" alt="'.$newsResult['title'].'" />
<h3><a href="press-releases/'.$newsResult["id"].'/'.$newsResult["title"].'.php">'.$newsResult["title"].'</a></h3>
'.substr($newsResult['descrip'],0,100).'
<p><a href="press-releases/'.$newsResult["id"].'/'.$newsResult["title"].'.php">Read more</a></p>
</li>';
}
echo '</ul>';
} else {
echo 'We currently have no press releases available';
}
There are two problems that I can see. First of all,
GROUP BYis an aggregate function, so it is used to combine multiple rows into one row in your result (for instance, if you wanted to see how many news items were written for a given month and year). Secondly, even if you were getting multiple records per time period, you are outputting a date header for every record that you pull from the database (ie. you would get duplicate headers if you have multiple news items from the same month and year).A better solution would be to collect all your active news items (without the
GROUP BYclause), and then build an array which you can then iterate over to output your page: