简体   繁体   English

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

[英]Trying to export MySQL query as CSV using PHP

I'm getting a warning 我收到警告

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, array given 警告:mysql_fetch_assoc()期望参数1为资源,给定数组

when trying to export a MySQL query result as CSV using PHP code like this: 当尝试使用以下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);
}

You're mixing mysql_* and mysqli_* API's. 您正在混合使用mysql_*mysqli_* API。 mysql_fetch_assoc() will not work with the mysqli_ API. mysql_fetch_assoc()不适用于mysqli_ API。 Your second while loop is the one using the wrong function call. 您的第二个while循环是使用错误函数调用的循环。

This line: 这行:

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

should be change to the correct function call: 应该更改为正确的函数调用:

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

mysql_fetch_assoc used to fetch a result row as an associative array here is more about mysql_fetch_assoc mysql_fetch_assoc用于作为关联数组获取结果行, 这里是有关mysql_fetch_assoc的更多信息

what you are trying to do is to pass $rows which is array while mysql_fetch_assoc expecting you to pass mysql_query 您想要做的是传递$rows数组,而mysql_fetch_assoc期望您传递mysql_query

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM