简体   繁体   中英

How would I select and display the most recently added rows from a SQL table?

I am making an extremely basic posting system, and I cant seem to figure out how to get the most recent rows from a certain table. I have tried other solutions offered here, but my posts were randomly placed. How would I accomplish this? My code is below.

function load_posts(){
$posts_sql = "SELECT * FROM posts";
    $posts_result = Phoenix\Database\Database::$database->query($posts_sql);
    while($row = $posts_result->fetch_assoc()){
        $posts_display = '

        <div class = "card" style = "width:500px">
            <div class = "card-body">
            <div class = "card-title">'. $row['username'] .'</div>
            <p>'. $row['content'] .'</p>
            </div>
        </div>
            
        ';

        echo $posts_display;
        }
}

Again, I want the posts to be displayed from most recent, to old.

You need to have information in each row that captures this information. The most common suspects are:

  • an auto-incrementing id
  • a creation date

Then you just ask the database to sort the results. For instance, if post_id is an auto-incremented id:

select p.*
from posts p
order by p.post_id;

SELECT * FROM TableName ORDER BY id DESC

// order by should be with primary key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM