Home > Database > Mysql Tutorial > How Can I Efficiently Export MySQL Query Results to CSV Using PHP?

How Can I Efficiently Export MySQL Query Results to CSV Using PHP?

Barbara Streisand
Release: 2024-12-13 01:05:10
Original
739 people have browsed it

How Can I Efficiently Export MySQL Query Results to CSV Using PHP?

Converting MySQL Queries to CSV in PHP

In PHP, exporting data from MySQL queries to CSV can be efficiently achieved without the use of temporary files. Here are two effective methods to accomplish this task:

Using MySQL's SELECT ... INTO OUTFILE:

This query directly outputs the result into a CSV file:

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
Copy after login

Using PHP Code:

This code selects the data, formats it in CSV format, and sends it as a response:

$select = "SELECT * FROM table_name";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

// Get header
for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

// Get data
while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}

// Send response
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Copy after login

Both of these methods effectively convert MySQL query results to CSV format in PHP, with the choice of approach depending on factors such as database size and desired flexibility.

The above is the detailed content of How Can I Efficiently Export MySQL Query Results to CSV Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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