Saturday 27 June 2015

Export MySQL table in CSV format using PHP

<?php
$link = mysql_connect($mysql_host,$mysql_user,$mysql_pass) or die('Could not connect: '.mysql_error());
mysql_select_db($mysql_db,$link) or die('Could not select database: '.$mysql_db);
$query = "SELECT * FROM $tablename ORDER BY id";
$result = mysql_query($query) or die("Error executing query: ".mysql_error());
$row = mysql_fetch_assoc($result);
$line = "";
$comma = "";
foreach($row as $name => $value)
{
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ";";
}
$line .= "\n";
$out = $line;
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result))
{
$line = "";
$comma = "";
foreach($row as $value)
{
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ";";
}
$line .= "\n";
$out.=$line;
}
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=listino.csv");
echo $out;
exit;
?>

0 comments:

Post a Comment