Export MySQL Table Data into CSV Format Using PHP

In this tutorial, we will see how to export mysql table data into CSV format to download and open into MS-excel.

Mostly this concept is used in ecommerce site to export data records into CSV format. In just one click of export CSV we will get our database table all records into CSV format and we can open it in MS-excel to see. Let Us see how it works.

Demo

For this export process we need PHP Snippet to perform some operation on Database Table.

In this snippet we used here header to make browser operation possible for download CSV file. We click on Export button, then a CSV file download which contains MySQL database Table records.

Here we have to set header with content-type , content-deposition and file name for CSV with .csv extension for download A CSV file. To get a better CSV format file put this code on top of the page.

<?php 
 mysql_connect("localhost","root","");
 mysql_select_db("test");

if(isset($_POST['export'])){

//Query From Table
$sql = mysql_query("select * from products");
$cols_total = mysql_num_fields($sql);
$output= '';

// Get All Field Name From Table
 for ($i=0; $i<$cols_total;$i++) {
$fieldname = mysql_field_name($sql, $i);
$output .= '"' . $fieldname . '",';
}
$output .="\n";

// Get Records from the table
while ($row = mysql_fetch_row($sql)) {
for ($i=0; $i<$cols_total;$i++) {
$output .='"' . $row[$i] . '",';
}
$output .="\n";
}
  //Download CSV 
  $file= "prod.csv";
  header('Content-Type: application/csv');
  header('Content-Disposition: attachment; filename='.$file);
  echo $output;
  exit;
   }
   ?>
   
<form method="POST">
<input type="submit" name="export" value="Export" />
</form>

Leave a Comment