Skip to content
Advertisement

How to show the Id number in descending order?

I am using PHP and I have to export the data from the database. I am using the below code which is working.

$sql = "SELECT `name`, `email`, `mobileno`, `data_of_added` FROM `emp` WHERE is_active=1 order by data_of_added DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll();

//Get the column names.
$columnNames = array();

//Open up a file pointer
 $fp = fopen('php://output', 'w');
 fputcsv($fp, array('id','Name', 'Email','Mobileno', 'Date of contact'));    
 fputcsv($fp, $columnNames);

// //Then, loop through the rows and write them to the CSV file.
 $i=1;
 foreach ($rows as $row) {
 $data = array('id'=>$i++,'name' =>$row['name'],'email' =>$row['email'],'mobileno' =>$row['mobileno'],'data_of_added' =>$row['data_of_added']);
    fputcsv($fp, $data);
 }

$fileName = 'export.csv';
 
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

fclose($fp);

I am getting all the records.

enter image description here

Notice that I am getting all the records in descending order and id is showing ascending `order.

This is my expected output:

enter image description here

How can I show the Id in descending order?

Advertisement

Answer

You can do this way easily with the help of count() and decrementing the $len by 1

 $len = count($rows);
 foreach ($rows as $row) {
    $data = array('id'=>$len--,'name' =>$row['name'],'email' =>$row['email'],'mobileno' =>$row['mobileno'],'data_of_added' =>$row['data_of_added']);
    fputcsv($fp, $data);
 }

Note: You could do that id order descending on your select query side but as you are already using order by data_of_added DESC so I guess above snippet will do the trick for you.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement