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 Using Two Different Methods?

Patricia Arquette
Release: 2024-12-21 04:54:10
Original
443 people have browsed it

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");
Copy after login

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";
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template