Home >>MySQL Tutorial >How to Export MySQL to CSV

How to Export MySQL to CSV

Export MySQL table to CSV using PHP

How to export MySQL table data into CSV file.

<?php
extract($_POST);
if(isset($save))
{
// Database Connection
$host="localhost";
$uname="root";
$pass="";
$database = "demo";	

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");	
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

	
// Fetch Record from Database

$output			= "";
$table 			= "users_csv"; // Enter Your Table Name(table from previous tutorial)
$sql 			= mysql_query("select * from $table");
$columns_total 	= mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++)
 {
	$heading	=	mysql_field_name($sql, $i);
	$output		.= '"'.$heading.'",';
}
$output .="n";

echo $output;
// Get Records from the table

while ($row = mysql_fetch_array($sql))
{
for ($i = 0; $i < $columns_total; $i++) 
{
$output .='"'.$row["$i"].'",';
}
$output .="n";
}

echo $output;
// Download the file

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

//echo $output;
//exit;


}	
?>

<form method="post">
	<input type="submit" value="Export Mysql In CSV" name="save"/>
</form>

No Sidebar ads