如何将mysql导出到csv包含所有表?
问题描述:
Following Code helps to export the particular table from mysql to CSV format.. But i need the code that helps to export to csv with all the table from mysql. Please anyone have the code. Please share it
<?php
$conn = mysql_connect('localhost', 'xxxx', 'yyyy') or die(mysql_error());
mysql_select_db('zzzz', $conn) or die(mysql_error($conn));
$query = sprintf('SELECT * FROM TABLENAME');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\|\
|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "
";
}
?>
答
Use this code SHOW TABLES
query returns the all tables in your selected db.
$tablesRes = mysql_query('SHOW TABLES',$conn);
while($row = mysql_fetch_row($tablesRes)){
$tables[] = $row[0];
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');
foreach($tables as $table){
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query, $conn) or die(mysql_error($conn));
//your csv code here
}