I have this code that works perfectly to export a table to a CSV file, but it does not insert header column name.
<?php
$host = 'host';
$mydatabase = 'db';
$user = 'user';
$pass = 'pass';
try {
$db = new PDO('mysql:host='.$host.';dbname='.$mydatabase, $user, $pass);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
$sql = 'SELECT * FROM table ORDER BY id ';
$stmt = $db->prepare($sql);
$stmt->execute();
if ($output != '') {
$output .= "\n";
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output .= '"'.$row['id'].'",';
$output .= '"'.$row['name'].'",';
$output .= '"'.$row['surname'].'",';
$output .= '"'.$row['etc'].'",';
$output .= "\n";
}
$file = 'table.csv';
$f = fopen($file, 'w');
fwrite($f, $output);
fclose($f);
It depends on what exactly you want.
Assuming that you only want a header if you have some data in the table, you can do it this way:
$sql = 'SELECT * FROM table ORDER BY id ';
$stmt = $db->prepare($sql);
$stmt->execute();
$fp = fopen('table.csv', 'w');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($data !== []) {
fputcsv($fp, array_keys($data[0]));
foreach ($data as $row) {
fputcsv($fp, $row);
}
}
fclose($fp);
However, most people will tell you that SELECT *
is a bad idea. You should list all the columns explicitly. If you can list the columns in SQL then you can also list them in your CSV generation script. Nothing wrong with a little duplication.
If you would like to have a header in your CSV file always even when there are no data rows, then you can just hardcode it.