Kelsey
Kelsey

Reputation: 921

PHP fputcsv not Outputting First Row From SQL Query (Outputs all Other Rows After the First Row)

I am using the very simple code below to export a CSV of all of my MySQL table's data, "members". However, there is a total of 560 rows in the MySQL table, but the CSV only shows 559 of the MySQL table's rows (it does not display the very first database's table's row). Does anyone know why this is, or perhaps what I can change in my code in order to fix this issue?

// 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

Upvotes: 2

Views: 632

Answers (1)

Oleg Imanilov
Oleg Imanilov

Reputation: 2751

You calling mysqli_fetch_assoc($sql); before while loop, which iterates over first row. You may change it to something like this:

// 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

In this case, you will reuse $row from first iteration.

Upvotes: 2

Related Questions