Search code examples
phpmysql

Sort and group results by date


I have a table with blog posts. I want to select the most recent posts and using PHP echo a divider between them similar to the example below. I was thinking about storing all results in PHP arrays and then echoing, is there an easier way via MySQL?

Thursday, Sept 8th
-----------------------
Post 1 
Post 2

Friday, Sept 9th
-----------------------
post 3
post 4

Solution

  • This is an idea: order by post_date and then only print it if changed. For this, your code needs to "remember" the current value in a dedicated variable

    <?php
    $sql = "SELECT * FROM posts ORDER by post_date DESC";
    $posts = $con->query($sql);
    
    $previous_date = "";
    foreach ($posts as $row){
        //here goes the date
        if($post['post_date'] != $previous_date){
            echo $post['post_date'];
            echo "<br>--------------------<br>";
            $previous_date = $post['post_date'];
        } 
        //here goes the post
        echo "Post:{$post['title']}<br>";
    }