How can I export mysql table to csv file and load it

Try exporting data to a CSV file from mysql. I took the following script, but the $ result variable has an error: mysql_num_fields reports that the provided argument 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);
}
+3
source share
1 answer

If you do not 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 request and then just do:

header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();
+4
source

All Articles