dphe5602
2014-04-30 09:39
浏览 75
已采纳

如何将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 "
";
    }
 ?>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanping6698 2014-04-30 10:03
    已采纳

    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
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题