Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

php - Display MySQL results by date

I have this mysql Table:

+--------------------+---------+-------+
|      date          | query   | count |
|--------------------+---------+-------|
|2012-11-18 09:52:00 | Michael |   1   |
|2012-11-18 10:47:10 |  Tom    |   2   |
|2012-11-17 15:02:12 |  John   |   1   |
|2012-11-17 22:52:10 |  Erik   |   3   |
|2012-11-16 09:42:01 |  Larry  |   1   |
|2012-11-16 07:41:33 |  Kate   |   1   |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

and so on. I can simply take results and order them by date in one row via this code:

$queries = mysql_query("SELECT * FROM my_tables ORDER BY date DESC LIMIT 20"); 
while($row = mysql_fetch_array($queries)){
    echo "Name ".$row['query']."";
}

But how to display elements from table ordered by specific date like this:

In 2012-11-18:
Michael
Tom

In 2012-11-17:
John
Erik

In 2012-11-16:
Larry
Kate

and so on. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is teh PHP code:

$query = mysql_query("SELECT date, query FROM table6 ORDER BY date DESC LIMIT 20");
$group_date = null;
while ($row = mysql_fetch_assoc($query)) {
    if ($group_date !== substr($row["date"], 0, 10)) {
        $group_date = substr($row["date"], 0, 10);
        echo "<h1>$group_date</h1>
";
    }
    echo "${row['query']}<br>
";
}

Output:

2012-11-18

Tom

Michael

2012-11-17

Erik

John

2012-11-16

Larry

Kate

Note that while this code "groups" rows by one column, it can easily be extended to group rows by multiple columns. Left as an exercise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...