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

如何将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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误