简体   繁体   中英

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

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);
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM