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

时间:2015-09-04 20:52:25

标签: php mysql csv

我收到警告

  

警告:mysql_fetch_assoc()期望参数1是资源,数组   给定

尝试使用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);
}

2 个答案:

答案 0 :(得分:2)

您正在混用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);

答案 1 :(得分:-1)

mysql_fetch_assoc用于获取结果行作为关联数组here is more about mysql_fetch_assoc

您要做的是传递$rows数组,mysql_fetch_assoc期待您通过mysql_query