-1

I am using fputcsv to export my database into the excel format. Currently it is showing all fields, including the id from the database. But I want Serial Numbers in the first column of the exported CSV file. The Database id series may change if some records are deleted from database. So I Need Serial numbers.

Is it possible ?

My current code is -

require_once("../db.php");

$contents="Database Id,Name,Amount,Cheque/Cash,Bank,Cheque Date,Branch,Address,Receipt No,Receipt Date\n";
$user_query = mysql_query("SELECT * from tablename ORDER BY RAND()");

$contents = strip_tags($contents);

header("Content-Disposition: attachment; filename=my_file_".date('d-F-Y').".csv");
$out = fopen('php://output', 'w');
fputcsv($out, array('Database Id', 'NAME', 'AMOUNT', 'CHEQUE/CASH DETAILS' , 'BANK' , 'CHEQUE DATE' , 'BRANCH', 'ADDRESS', 'RECEIPT NUMBER', 'RECEIPT DATE'));

while ($row = mysql_fetch_assoc($user_query)) {
   fputcsv($out, $row);
}
Patrick G
  • 487
  • 2
  • 12
chplab
  • 49
  • 8
  • You wrote that code, but you can't increment a variable in that `while` loop? – N.B. Sep 18 '14 at 13:44
  • then any other solution for this ? – chplab Sep 18 '14 at 13:45
  • May I Know Why Negative Vote Is There For My Question ? – chplab Sep 18 '14 at 13:46
  • It's not useful. I don't think it's helpful nor interesting, so I marked it as such. Also, I've no idea what's Wit This Type Of Expressing Your Self, but it's extremely unprofessional. What you're asking is taught in every programming book at about 2nd page - increment a variable in a loop. If you wrote the code above, you should be able to do it yourself. If you haven't, that means you consider people here programmers for free - that's bad. – N.B. Sep 18 '14 at 13:48

1 Answers1

1

You need to implement a counting variable

$i = 1;

and increment it on every step in your loop:

$i += 1;

Now you need to insert it into the first place of the array you pass to the fputcsv function. Something like this:

fputcsv($out, array($i, $row["Database Id"], $row["Name"], ...));

If you are having trouble finding the indexes of your $row variable, just use the print_r function. You will get the whole array with all it's indexes.

Patrick G
  • 487
  • 2
  • 12