以下代码有助于将特定表格从mysql导出为CSV格式。 但我需要的代码有助于从mysql导出到csv 所有表。请有人有代码。请分享
<?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('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
答案 0 :(得分:0)
使用此代码SHOW TABLES
查询将返回所选数据库中的所有表。
$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
}