Ns789
Ns789

Reputation: 541

How to display the serial number of the table rows in descending order in php?

I am looking way to sort the serial number of the table in descending order. I am using a here simple while loop, with a counter variable inside it.

Code sample:

       $i= 0;
       while(condition)
       {
           $i++; 
         echo "<td>".$i."</td>";
       }

Output:

Screen shot showing output of while loop

I am not using an autoincrement column here. I just want it with a simple counter, but in descending order.

example:

#
10
9
8
7
6
5
4
3
2
1

Any help is highly appreciated.

Upvotes: 0

Views: 1811

Answers (3)

Feshibaba
Feshibaba

Reputation: 101

If you are fetching from MYSQL Database and you're using PDO to connect to Database

//COUNT THE TOTAL NUMBER OF ROWS RETURNED
$sql = "SELECT COUNT(*) FROM all_tnxs ORDER BY id DESC";
$stmt = $con->query($sql);
$stmt_num_rows = $stmt->fetch();
$tot_rows = array_shift($stmt_num_rows);
$sn = $tot_rows

while(){
 $sn--;
 echo '<td>' . $sn . '</td>';
}

So whatever the total number of rows you have - fetching from the database it'll countdown to '0'using the while loop. I have been looking for this for long but later figured it out myself so I decided to drop it here for anyone it might be helpful to...

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57131

If you already have loop outputting the 1-10 version, you could simple change the output to show 11 minus the current count...

echo "<td>".(11-$i)."</td>";

Or to change the whole code, you could start at 11 and decrement the counter each time and output it that way

$i= 11;
while($i>0)
{
    $i--;
    echo "<td>".$i."</td>";
}

Upvotes: 2

ScaisEdge
ScaisEdge

Reputation: 133380

count first and after do a loop in reverse order

   $i= 0;
   while(condition)
   {
       $i++; 

   }
   for ( cnt= $i, $i>= 0, $i--){
         echo "<td>".$cnt."</td>";
   }

Upvotes: 1

Related Questions