Grouping query entries by DATE loop?

So I query the database and it returns this: http://i56.tinypic.com/voyf4k.png

You’ll notice that for each row there is a DATE and a comment. So let’s say there a couple entries in my database that the have DATES “2011-04-08” and then there are some rows that the have DATE “2011-04-07” and then “2011-04-05”, etc.

I would like to be able to separate all of the entries by DATE when I query the database, so that way it will look like this: http://i51.tinypic.com/15o8kex.png

First, you need to sort records by date field in your sql query. Then within a loop (while fetching records) you can do this grouping:
[php]$r = mysql_query("SELECT * FROM mytable ORDER BY Date");
$previous_date = ‘none’;
echo ‘

’;
while($row = mysql_fetch_array($r)){
if($previous_date != $row[‘Date’]){ // true on the 1st iteration
// display group header
echo '<tr><td colspan="3">Date: '.date('Y-n-d',$row['Date']).'</td></tr>';
$previous_date = $row['Date'];

}

// display regular row
echo ‘

’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘’;
}
echo ‘
In: ‘.date(‘Y-n-d H:i:s’,$row[‘Date’]).’Out: ‘.date(‘Y-n-d H:i:s’,$row[‘DateOut’]).’Comment: ‘.htmlspecialchars($row[‘Comment’]).’
’;[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service