trying to output query to csv

I am trying to output my query to csv and I don’t get any errors, but I also don’t get any data. It is an empty file

[php]//mysql connection
info here

//Connect to MySQL using PDO.
$pdo = new PDO(“mysql:host=$host;dbname=$database”, $user, $password);

//Create our SQL query.
$sql = "SELECT status, orderid, DATE_FORMAT(FROM_UNIXTIME(date), ‘%m/%d/%Y’) as orderdate, email, b_state, s_country, subtotal FROM xcart_orders where date BETWEEN $BeginDate AND $EndDate AND (status =‘C’ OR status =‘P’) ";

//Prepare our SQL query.
$statement = $pdo->prepare($sql);

//Executre our SQL query.
$statement->execute();

//Fetch all of the rows from our MySQL table.
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

//Get the column names.
$columnNames = array();
if(!empty($rows)){
//We only need to loop through the first row of our result
//in order to collate the column names.
$firstRow = $rows[0];
foreach($firstRow as $colName => $val){
}
}

//Setup the filename that our CSV will have when it is downloaded.
$fileName = ‘EmailAddresses-export.csv’;

//Set the Content-Type and Content-Disposition headers to force the download.
header(‘Content-Type: application/excel’);
header(‘Content-Disposition: attachment; filename="’ . $fileName . ‘"’);

//Open up a file pointer
$fp = fopen(‘php://output’, ‘w’);

//Start off by writing the column names to the file.
fputcsv($fp, $columnNames);

//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
fputcsv($fp, $row);
}

//Close the file pointer.
fclose($fp);
?>[/php]

Any help is appreciated.

Hi

I have tried executing this code and it produces a non-empty CSV file. Most likely your query is not returning any rows? Try executing the the SQL via a different interface (PHPMyadmin, mysql via command line/terminal) to ensure that you are returning some results and not zero rows.

Yes, that was it. I forgot that I have two forms on the referring page and so I needed to change the date variable I was using. Thanks for the head bump to get me thinking straight.

Sponsor our Newsletter | Privacy Policy | Terms of Service