Sunday, November 25, 2007

Exporting mysql data to csv

Today I'm going to discuss the opposite of the previous post. Here it is :

/*some checking here like if the user is logged in, this is important in cases where we don't want other users to get hold of the data*/

//connect to the mysq;
define('host', 'localhost'); //Mysql Server name
define('database', 'dbname'); //Mysql Database name
define('user', 'dbuser'); //Mysql Username
define('password', 'dbpassword'); //Mysql Password
$dbtable = "dbtable";
$connection = mysql_connect(host,user,password);
$db = mysql_select_db(database,$connection);

$sql = mysql_query("select * from ".$dbtable.");

$fields = mysql_list_fields("yourdatabasename",$dbtable);
$columns = mysql_num_fields($fields);
$output = '';

// Put the name of all fields
for ($i = 0; $i < $columns; $i++)
{
$l=mysql_field_name($fields, $i);
$output .= '"'.$l.'",';
}

$output .="\n";

//we now put all values from table
while ($l = mysql_fetch_array($sql))
{
for ($i = 0; $i < $columns; $i++)
{
$output .='"'.$l["$i"].'",';
}

$output .="\n";
}

// Output to browser with appropriate mime type, you choose
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=yourcsvfile.csv");
echo $output;
exit;

?>

This script will prompt for a download for the csvfile named yourcsvfile.csv which contain all the columns and entries from the table dbtable.

No comments: