在 While 循环中反转表格行

Bru*_*uno 0 php mysql

我将行附加到具有分页的表中。我的数据库查询按 ASC 排序,这是我需要的,但记录的顺序应该在每个页面上颠倒。所以第一页应该是最新的记录,但该页面应该在该页面上从最旧到最新排序。所以我的表应该是这样的:

Page 1
Date    Type    Registration
-----------------------------
9 Jan    Van       ZZASA
14 Jan    Car      ASDFS
19 Jan    Van      ASDFS


Page 2
Date    Type    Registration
-----------------------------
1 Jan    Van       ZZASA
4 Jan    Bus       ASDFS
5 Jan    Van       ASDFS
Run Code Online (Sandbox Code Playgroud)

我在 WHILE 循环中添加行,如下所示:

    while($row = mysqli_fetch_assoc($result)){      
        $tablerows .= '<tr>
                          <td>'.$row['date'].'</td>
                          <td>'.$row['type'].'</td>
                          <td>'.$row['registration'].'</td>
                       </tr>
   }
Run Code Online (Sandbox Code Playgroud)

如果我能在 while 循环中颠倒顺序,它就会完美运行,但我不知道该怎么做。如果我将每个都添加到数组中然后使用 array_reverse 函数,它会起作用吗?

N'B*_*yev 5

1.SQL解决方案(推荐)

ORDER BY在您的查询中使用:

ORDER BY date DESC
Run Code Online (Sandbox Code Playgroud)

2.PHP解决方案

首先,使用mysqli_fetch_all()以下命令获取所有结果集:

$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
Run Code Online (Sandbox Code Playgroud)

然后,使用array_reverse()

$reverse_rows = array_reverse($rows);
Run Code Online (Sandbox Code Playgroud)