KittenMittons
KittenMittons

Reputation: 73

Printing MySQL query results to CSV file in PHP

I'm having a problem writing the results of a MySQL query to a file using php. There are definitely results from the search, and the file is created, but when you open the file it's empty.

I think it's something to do with how I'm writing to the file, but I'm not sure.

$result = mysql_query($compsel);
if (!result) die("unable to process query: " . mysql_error());
$fp = fopen('results.csv', 'w');
mysql_data_seek($result, 0); //set data pointer to 0
$rw = mysql_fetch_array($result, MYSQL_ASSOC);
print_r($rw);
foreach ($rw as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

Thanks in advance!

Upvotes: 0

Views: 2965

Answers (1)

arcee123
arcee123

Reputation: 211

Here's an example:

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

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

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

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

You can modify it to suit your needs. Source: http://code.stephenmorley.org/php/creating-downloadable-csv-files/

Upvotes: 1

Related Questions