php - 尝试使用 PHP 将 MySQL 查询导出为 CSV

标签 php mysql csv

我收到警告

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, array given

当尝试使用如下 PHP 代码将 MySQL 查询结果导出为 CSV 时:

public static function exportLocationCSV($id){
        $sql =<<<EOF
            SELECT col1, col2, col3
            FROM table1
            JOIN table2 ON table1.col0=table2.col0 
            WHERE table1.col0 = $id;
EOF;


        // output headers so that the file is downloaded rather than displayed
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=data.csv');

        // create a file pointer connected to the output stream
        $output = fopen('php://output', 'w');

        // output the column headings
        fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

        $query_export= self::$db_connection->query($sql);
        $rows = array();
        while($r = mysqli_fetch_assoc($query_export)){
            $rows[] = $r;
        }

        // loop over the rows, outputting them
        while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
}

最佳答案

您正在混合 mysql_*mysqli_* API。 mysql_fetch_assoc() 不适用于 mysqli_ API。您的第二个 while 循环使用了错误的函数调用。

这一行:

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

应该更改为正确的函数调用:

// loop over the rows, outputting them
foreach($rows AS $row) fputcsv($output, $row);

关于php - 尝试使用 PHP 将 MySQL 查询导出为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32406417/

相关文章:

.net - .NET 中的 .CSV 到 .MDB 转换

php - 在构造的 MYSQL 查询中转义 "?"

一个过程中的 MySQL 多个命令

html - 如何将 html 表格数据导出为 .csv 文件?

mysql - 在 MySql 触发器中运行系统调用

php - 当有两个匹配数据时,只获取一个 Json 对象响应?

Ruby CSV.parse 在遇到引号时非常挑剔

php - pdflib-sh : phpize: command not found

php - Azure PHP 错误 500

javascript - 加载页面,在 JavaScript 警报时给出变量