Skip to content

Instantly share code, notes, and snippets.

@matteomattei
Created July 8, 2014 08:09
Show Gist options
  • Save matteomattei/301dfbdd3583ce9c2b5e to your computer and use it in GitHub Desktop.
Save matteomattei/301dfbdd3583ce9c2b5e to your computer and use it in GitHub Desktop.
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;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment