Created
September 9, 2015 17:22
-
-
Save sanjaybhowmick/db19b04f460f72bb6ac5 to your computer and use it in GitHub Desktop.
Convert your MySQL database table to CSV format in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
exit; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment