Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i export mysql table to csv file and download it

Tags:

php

drupal

Am tryng to export data to csv file from mysql. I took the following script but the $result variable have error : mysql_num_fields tells the argument supplied is not valid

$filename = 'myfile.csv';
$result = db_query("SELECT * FROM {loreal_salons}");


drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++) {
    $header[] = mysql_field_name($result, $i);
}
print implode(',', $header) . "\r\n";

while ($row = db_fetch_array($result)) {
    foreach ($row as $value) {
        $values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
    }
    print implode(',', $values) . "\r\n";
    unset($values);
}
like image 517
Mamadou Avatar asked Jan 18 '26 09:01

Mamadou


1 Answers

If you don't mind using a temporary file, you can do:

SELECT *
INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM loreal_salons

as your query, then simply do:

header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();
like image 179
Marc B Avatar answered Jan 19 '26 23:01

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!