"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Export MySQL Query Results to CSV Using PHP?

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

Published on 2024-12-21
Browse:794

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;

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 

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3