Pages

Sunday, January 3, 2010

MySQL table to CSV – PHP Script

Hello Friends !!

If you want to export data from MySQL table to CSV file ,then don’t worry. I will provide you one script. When you run this script, data in table will be stored in CSV file.

Here is the PHP script. You have to just copy that code and paste in your PHP file and run that file.

$host = ‘hostaddress’;
$user = ‘username’;
$pass = ‘password’;
$db = ‘DB name’;
$table = ‘table name’;
$file = ‘export’;

$link = mysql_connect($host, $user, $pass) or die(“Can not connect.” . mysql_error());
mysql_select_db($db) 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'].”; “;
$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;
?>

No comments: