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; $iBoth 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.
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