Skip to content

Instantly share code, notes, and snippets.

Created September 9, 2015 17:22
What would you like to do?
Convert your MySQL database table to CSV format in PHP
$rsSearchResults = mysql_query("SELECT * FROM tablename order by id DESC") or die(mysql_error());
$out = '';
$fields = @mysql_list_fields('databasename','tablename');
$columns = @mysql_num_fields($fields);
// Put the name of all fields
for ($i = 0; $i < $columns; $i++)
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
$out .="n";
// Add all values in the table
while ($l = mysql_fetch_array($rsSearchResults))
for ($i = 0; $i < $columns; $i++)
$out .='"'.$l["$i"].'",';
$out .="n";
// Output to browser with appropriate mime type, you choose
@header("Content-type: text/x-csv");
@header("Content-Disposition: attachment; filename=filename.csv");
echo $out;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment