You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数据库查询结果按从新到旧排序展示

How to Sort Database Results from Newest to Oldest

Hey there! The fix here is straightforward—you just need to adjust your SQL query to explicitly sort the results in descending order. Right now, your code is pulling data without specifying an order, so it’s returning rows in whatever default order the database uses (which isn’t guaranteed to be newest first).

Here’s how to implement this:

Step 1: Pick your sorting column

First, identify which column in your table tracks when records were added. Common options are:

  • A date/time column like created_at or timestamp
  • An auto-incrementing primary key (like id, since newer records get higher IDs)

Step 2: Add ORDER BY to your SQL query

Modify your SELECT statement to include ORDER BY [your_column] DESC. The DESC keyword tells the database to sort from highest (newest) to lowest (oldest) values.

Here’s how this fits into your existing PHP code:

// Create connection
$connection = new mysqli($server, $user, $pass, $dbname);

// Check connection
if ($connection->connect_error) {
    die("Error on connection: " . $connection->connect_error);
}

// Updated query with sorting (replace placeholders with your actual table/column)
$sql = "SELECT * FROM your_table_name ORDER BY created_at DESC";
$result = $connection->query($sql);

// Loop through results to build your table
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Replace with your table row output logic
        echo "<tr><td>" . $row['id'] . "</td><td>" . $row['content'] . "</td></tr>";
    }
} else {
    echo "<tr><td colspan='2'>No records found</td></tr>";
}

// Clean up connection
$connection->close();

Quick notes:

  • If you don’t have a date/time column, using ORDER BY id DESC works perfectly (as long as you’re not manually setting IDs, which you shouldn’t be for auto-increment fields).
  • Always replace your_table_name and created_at with your actual table and column names.
  • For security, use prepared statements if you ever add user input to your query (though a static SELECT like this is safe as-is).

That’s it—your table will now display the newest records at the top!

内容的提问来源于stack exchange,提问作者paradox3ed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:25:01