• flickr
  • linkedin
  • twitter
  • rss
Export a table to CSV with php/mysql

Export a table to CSV with php/mysql

include("db_conn.php");

$file = 'Export';

$result = mysql_query("SHOW COLUMNS FROM [[TABLE]]");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM [[TABLE]]");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].";";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
Tech Reference:

Larry's a 30-something chap interested in travel, being a dork and changing the world via less boring training.

Leave a reply