How to export SQL table in csv with PHP

In this post we will see how to export SQL table in csv format with PHP in simplest way. First connect to your server and database as usual and write down following code to export your desired table in csv format.

$sql = mysqli_query("select * from `YourTable` ");
$countColumns = mysqli_field_count($sql); // get total columns

for ($i = 0; $i < $countColumns; $i++) {
  $column = mysqli_fetch_field_direct($sql, $i);  // get field name
  $csv.= '"'.$column.'",';
}
$csv.="\n";

while ($row = mysqli_fetch_array($sql)) {
  for ($i = 0; $i < $countColumns; $i++) {
  $csv.='"'.$row["$i"].'",';
}
$csv.="\n";
}

$filename = "Export.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $csv;
exit;
This is all you need to export the whole table in csv but if you need some specific columns to export then instead of getting field names from table write down specific field names and get data from same fields.
Tags: CSV
comments powered by Disqus