Wednesday, December 18, 2013

how to export mysql table as csv using php?


Use the below code snippet as it is,just make sure to include your config file which has connection with the database.
make a file named generate.php .
<?php
include("config.php"); //config file containing connection to your database,you can name it whatever you want.
// Fetch Record from Database

$output            = "";
$table             = "mytable"; // Enter Your Table Name
$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";

// Get Records from the table

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

// Download the file

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

echo $output;
exit;
   
?>

If you want to generate csv file on click of any button or link.Just give path of this file in the link.Like:
<a href="generate.php">generate csv</a>

No comments:

Post a Comment