Home >Backend Development >PHP Tutorial >How to Export MySQL Query Results as CSV in PHP Using Two Different Methods?
How to Export MySQL Query Results as CSV in PHP
Exporting data from a MySQL database as a CSV can be achieved through various methods. Here are two efficient approaches:
Using MySQL's SELECT INTO OUTFILE
This method allows you to directly export query results to a CSV file on the server:
$query = "SELECT * FROM my_table"; $csv_path = "c:/mydata.csv"; $result = mysql_query("SELECT * INTO OUTFILE '" . $csv_path . "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' FROM my_table");
Creating a CSV Manually
Alternatively, you can create the CSV file manually using PHP:
$select = "SELECT * FROM table_name"; $export = mysql_query($select) or die("Sql error : " . mysql_error()); $fields = mysql_num_fields($export); // Generate the header line with field names for ($i = 0; $i < $fields; $i++) { $header .= mysql_field_name($export, $i) . "\t"; } // Process each row of the query results while ($row = mysql_fetch_row($export)) { $line = ''; foreach ($row as $value) { if (empty($value)) { $value = "\t"; } else { $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim($line) . "\n"; } $data = str_replace("\r", "", $data); // Set the HTTP headers for CSV download header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=your_desired_name.xls"); header("Pragma: no-cache"); header("Expires: 0"); // Output the CSV print "$header\n$data";
The above is the detailed content of How to Export MySQL Query Results as CSV in PHP Using Two Different Methods?. For more information, please follow other related articles on the PHP Chinese website!