Sunday 3 November 2013

Download MySQL Table Records To CSV File Using PHP

Try the following code for download mysql table records as CSV file.

<?php

mysql_connect("localhost", "root", "") or die("Connection failed! " . mysql_error());
mysql_select_db("database") or  die("Error in database connection " . mysql_error());


$output = "";
$table = ""; // Enter Your Table Name Here
$sql = mysql_query("select * from $table");
$total_columns = mysql_num_fields($sql);

// First you get all field names

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

// Get the all values from database

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

// Download the CSV file

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

echo $output;
exit;

?>

No comments:

Post a Comment