Search code examples
phpmysqlexport-to-excel

Adding serial number in first column while exporting mysql as excel via php


I am using following php code to export mysql data to excel via php script.

As Id in mysql table are not serially as some rows were deleted as per need.

So I want to add serial number in first column for records from mysql. What can be added in below code to achieve this ?

Your help is appreciated.

my current code is as follows :

<?php
include("db.php");

$file_name = "My-Records-" . date('d-F-Y-H-i-s') . ".xls";

function cleanData(&$str){
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
     if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
function modify($str) {
    return ucwords(str_replace("_", " ", $str));
}

# Header information
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Type: application/vnd.ms-excel");

$flag = false;
$result = $database->get_results("SELECT lname, fname, mobile, email, form_date FROM myTable") or die('Connection failed!');
foreach($result as $row){
    if(!$flag){
      // display field/column names as first row
       $old_states1 = array_keys($row);
       $old_states2 = array_map("modify", $old_states1);
       $states = implode("\t", $old_states2 ) . "\r\n";

       print $states;
      $flag = true;
    }
     array_walk($row, 'cleanData');
    print implode("\t",  array_values($row)) . "\r\n";
}
exit;
?>

Solution

  • Change your code a bit to get what you want:

    // ...
    
    // NEW CODE HERE
    $row_index = 0;
    
    foreach ($result as $row) {
        // NEW CODE HERE
        $row = array_merge(['id' => ++$row_index], $row);
           
        if (!$flag) {
           // display field/column names as first row
           $old_states1 = array_keys($row);
           $old_states2 = array_map("modify", $old_states1);
           $states = implode("\t", $old_states2 ) . "\r\n";
    
           print $states;
           $flag = true;
        }
        
        array_walk($row, 'cleanData');
        
        print implode("\t",  array_values($row)) . "\r\n";
    }
    

    Full demo code