Php – MySQL + PHP (grouping by date)

group-byMySQLPHPsql

I'm trying to output a list of different itmes grouped by the date they were stored in the database (unix timestamp).

I'd need help with both MySQL (query) and PHP (output).

MySQL table

id | subject | time
1 | test1 | 1280278800
2 | test2 | 1280278800
3 | test3 | 1280365200
4 | test4 | 1280451600
5 | test5 | 1280451600

OUTPUT

Today
test5
test4

Yesterday
test3

July 28
test2
test1

I'd appreciate any help on this. Thanks!;-)

Best Answer

You can convert your unix timestamp to a date using DATE(FROM_UNIXTIME(time)). This will output something like 2010-07-30.

The following should group by the date.

SELECT id, subject, time, DATE(FROM_UNIXTIME(time)) AS date_column
GROUP BY date_column

Edit: Didn't read your question correctly.

For this I would just run a standard SELECT and ORDER BY time DESC.

Then do the grouping with PHP.

$lastDate = null;

foreach ($rows as $row) {
    $date = date('Y-m-d', $row['time']);
    $time = date('H:i', $row['time']);

    if (is_null($lastDate) || $lastDate !== $date) {
        echo "<h2>{$date}</h2>";
    }

    echo "{$time}<br />";

    $lastDate = $date;
}