export some mySQL columns to CSV file

I am trying to export some columns of a MySQL table to a csv file using PHP. So far I’ve come up with the following code, which prints out the data on the “tabella” file in /localhost.
The problem is that it returns an empty csv file. I can’t understand why.
Any ideas out there? Thanks!

[php]<?php
// create a file pointer connected to the output stream
$output = fopen(‘tabella’, ‘w’);
// output the column headings
fputcsv($output, array(‘giorno’, ‘mese’, ‘anno’, ‘descrizione’, ‘durata’));
// fetch the data
mysql_connect(‘localhost’, ‘root’, ‘’);
mysql_select_db(‘ore’);
$rows = mysql_query(‘SELECT giorno,mese,anno,descrizione,((((ora_fine60)+(min_fine))-((ora_ini60)+(min_ini)))/60) FROM consuntivo’);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)){
fputcsv($output, $row);
}
header(‘Content-Type: text/csv’);
header(‘Content-Disposition: attachment; filename=tabella.csv’);
fclose($output);
?>[/php]

Try outputting to the screen before you write to the file. You shouldn’t need the loop, fputcsv () takes an array as a parameter, so there is no need to loop throught them.

Try

[php]fputcsv($filename, $rows)[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service