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

PHP如何将数据库查询的5条最新结果显示在列表底部而非顶部

PHP聊天记录排序需求实现方案

方案1:SQL层面完成排序(更推荐)

通过嵌套查询先取出最新的5条记录,再对这5条记录做升序排序,即可实现旧记录在上、最新记录在底部的效果,仅需要修改SQL语句即可,原有循环输出逻辑无需调整:

<?php

// 修改后的SQL语句
$sql = "SELECT * FROM (SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC LIMIT 5) AS latest_chats ORDER BY `id` ASC";

$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
    echo "<p>";
    echo "<span class = 'usr'>".$row['user_name']."</span>";
    echo "<br>";
    echo $row['message'];
    echo "<br>";
    if($row['Date'] === date("Y-m-d")){
      echo "Today ";
    }
    else{
      echo $row['Date'];
    }

    echo $row['Time'];
    echo "</p>";
  }
}
else{
  echo "No messages were found!";
}

?>

方案2:PHP层面反转结果集

如果不想修改SQL语句,可以先把查询到的降序结果存入数组,反转数组后再输出:

<?php

$sql = "SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5";
$result = mysqli_query($con, $sql);
$chats = [];
if(mysqli_num_rows($result) > 0){
  // 先把结果存入数组
  while($row = mysqli_fetch_assoc($result)){
    $chats[] = $row;
  }
  // 反转数组,顺序变为旧记录在前、新记录在后
  $chats = array_reverse($chats);
  // 循环输出
  foreach($chats as $row){
    echo "<p>";
    echo "<span class = 'usr'>".$row['user_name']."</span>";
    echo "<br>";
    echo $row['message'];
    echo "<br>";
    if($row['Date'] === date("Y-m-d")){
      echo "Today ";
    }
    else{
      echo $row['Date'];
    }

    echo $row['Time'];
    echo "</p>";
  }
}
else{
  echo "No messages were found!";
}

?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:45:05