How to Export Mysql table in CSV format.?


In the  previous post you see  how to Import an Excel file in Mysql database . Now In this tutorial, we will see how to Export or Download Mysql table in Excel Sheet form.
The CSV  stands for comma separated values. You often use the CSV file format to exchange data between applications such as Microsoft Excel, Google Docs, etc.

In previous post we create a mysql table excel_sheet . in  the table excel_sheet we create two coloums (category and website).

The following query selects website and category from the  excel_sheet table and put all records into list.csv file.

Also Read :
PHP Login Script With Remember me.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript
Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?


in download.php page we make a database connection. and inserting the data of mysql table (excel_sheet) into a file.

$db = mysqli_connect("localhost", "root", "", "test_excel");

$result = mysqli_query($db, "SELECT * from excel_sheet";);

header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=\"list.csv\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);

$output = fopen('php://output', 'w');

    fputcsv($output, array('website','category'));

while ($row = mysqli_fetch_assoc($result))
    fputcsv($output, $row);


Keep Learning…