我收到警告
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/