我使用下面非常简单的代码导出我所有MySQL表格数据的CSV,"成员"。但是,MySQL表中总共有560行,但CSV只显示了MySQL表的559行(它没有显示第一个数据库的表行)。有谁知道为什么会这样,或者为了解决这个问题,我可以在代码中修改一下?
// BEGIN EXPORT ALL FROM EDITOR
if(isset($_POST['export_csv'])) {
$today_date = date('Y-m-d_h-i-s-a', time());
$FileName = "download/report_mailing_list_export_".$today_date.".csv";
$file = fopen($FileName,"w");
$sql = mysqli_query($dbc, "SELECT * FROM member WHERE memberid != 1 AND deleted=0 AND website = 0 ORDER BY last_name, first_name DESC");
$row = mysqli_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
while($row = mysqli_fetch_assoc($sql)){
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
header("Location: $FileName");
}
// END EXPORT
答案 0 :(得分:2)
你调用mysqli_fetch_assoc($ sql);在while循环之前,迭代第一行。您可以将其更改为以下内容:
// BEGIN EXPORT ALL FROM EDITOR
if(isset($_POST['export_csv'])) {
$today_date = date('Y-m-d_h-i-s-a', time());
$FileName = "download/report_mailing_list_export_".$today_date.".csv";
$file = fopen($FileName,"w");
$sql = mysqli_query($dbc, "SELECT * FROM member WHERE memberid != 1 AND deleted=0 AND website = 0 ORDER BY last_name, first_name DESC");
$row = mysqli_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
do {
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
} while($row = mysqli_fetch_assoc($sql));
fclose($file);
header("Location: $FileName");
}
// END EXPORT
在这种情况下,您将从第一次迭代中重用$row
。