phpmysqlfputcsv

fputcsv creating only column headers


I am trying to export data from a MySQL table as a CSV which my client needs to email away on a regular basis.

This is what my PHP file contains:

require('db.php');

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=stoneleigh.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('CLUB NAME', 'NUMBER', 'TITLE', 'TYPE', 'FORENAME', 'SURNAME', 'ADDRESS1', 'ADDRESS2', 'ADDRESS3', 'ADDRESS4', 'POSTCODE', 'PHONE', 'EMAIL', 'MOBILE'));

//create query
$sql = "SELECT Club_Name,BHS,Title,Type,Forename,Surname,Address1,Address2,Address3,Address4,Postcode,Phone,Email,Mobile FROM tvrc_members WHERE Current = '1'";
$rows = $conn->query($sql);

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

require('foot.php');

Unfortunately when I link to my PHP file, it downloads a CSV file that only contains the column headers and no actual data below, any help appreciated. Thanks.


Solution

  • As per @berend comment, I changed my last line to

    while ($row = $rows->fetch_assoc()) {fputcsv($output, $row);}
    

    and this works.