Skip to content

Export a Table from MySQL Database with PHP Page

by Jon on November 24th, 2009

I just put together this page that will take a variable to export a table from a mySQL server. This is good if you have a website that stores data for people, this will give them the ability to export the data themselves without having to ask you for it.

Save this page as dataexport.php and to pass the table name to it use the following format for the url.

http://localhost/dataexport.php?tablename=name_of_table this will give you the ability to download the table in a csv format.


$db_user = “db_username”;
$db_pass = “db_password”;
$db_host = “localhost”;
$db_load = “databasename”;

$dbtable = $_GET[‘tablename’];
$table = $dbtable;
$file = ‘export’;

$link = mysql_connect($db_host, $db_user, $db_pass) or die(“Can not connect.” . mysql_error());
mysql_select_db($db_load) or die(“Can not connect.”);

$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’] . “,”;
$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 = $table.”_”.date(“Y-m-d_H-i”,time());
header(“Content-type: application/”);
header(“Content-disposition: csv” . date(“Y-m-d”) . “.csv”);
header( “Content-disposition: filename=”.$filename.”.csv”);
print $csv_output;

From → Linux

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS

%d bloggers like this: