0

I have some code here that exports to a csv file. I connected to the database and saw that there was well over 30 entries or so. But I'm only getting one in the csv file. The top part gets the headings for the file and the bottom the values, the values array is only returning one array and putting it into the file. I'm not sure what's causing this issue. Anny suggestions would be greatly appreciated.

<?php
$FileName = "mro_export_".date("Y-m-d_H-i",time()).".csv";
$file = fopen($FileName,"w");

$sql = mysql_query("SELECT * FROM `$table` LIMIT 11");
$row = mysql_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
    $HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
$ValuesArray=array();
foreach($row as $name => $value){
    $ValuesArray[]=$value;
}
fputcsv($file,$ValuesArray);
fclose($file);

header("Location: $FileName");
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Alex Howell
  • 89
  • 2
  • 14
  • You're only calling `mysql_fetch_assoc()` once, so you only get one row from the DB. – Barmar Aug 16 '14 at 00:36
  • FYI, your two `foreach` loops are equivalent to `$HeadingsArray = array_keys($row)` and `$ValuesArray = array_values($row)`. – Barmar Aug 16 '14 at 00:37

1 Answers1

1

You need to call mysql_fetch_assoc in a loop to get all the rows.

<?php
$FileName = "mro_export_".date("Y-m-d_H-i",time()).".csv";
$file = fopen($FileName,"w");

$sql = mysql_query("SELECT * FROM `$table` LIMIT 11") or die(mysql_error());
$first_line = true;
while ($row = mysql_fetch_assoc($sql)) {
    if ($first_line) {
        // Save headings alon
        fputcsv($file, array_keys($row));
        $first_line = false;
    }
    fputcsv($file, array_values($row));
}
fclose($file);

header("Location: $FileName");
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612