Skip to content
Advertisement

Reverse Table rows in While Loop

I am appending rows to a table that has pagination. My db query sorts by ASC which is what I need but the order of records should be reversed on each page. So the first page should be the newest records but that page should be ordered from oldest to newest on that page. So my table should look like this:

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

I am adding the rows in a WHILE loop like this:

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

If only I could reverse the order during the while loop it would work perfect but I am not sure how to do it. Would it work if I add each to an array and then use an array_reverse function?

Advertisement

Answer

Would it work if I add each to an array and then use an array_reverse function?

It makes sense. You can use array_reverse function to reverse an array. And implode to convert to a string, e.g:

$tablerows = array_reverse($rows);
$tablerows = implode('', $tablerows);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement