Are you looking to export your mydal data in .csv file using simple PHP code, then please keep your close attention in this post How to Export Data in .CSV File From Mysql Using PHP. CSV (comma separated values) is most widely supported file format for using data between different applications.
PHP fputcsv() function which will accepts array parameter of database results to coverted into the CSV format and download in .csv file:
1 |
fputcsv($output, $row); |
Below code will ensure your browser offers to download the file instead of displaying in browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<?php /** * Description: Export data from mysql table in .csv file * @author: Prem Tiwari */ // database variables $hostname = "localhost"; $user = "XXXXXXXXX"; $password = "XXXXXXXXX"; $database = "XXXXXXXXX"; // Database connection mysql_connect($hostname, $user, $password) or die('Could not connect: ' . mysql_error()); mysql_select_db($database) or die ('Could not select database ' . mysql_error()); // define file format header('Content-Type: text/csv; charset=utf-8'); // define your filename header('Content-Disposition: attachment; filename=your-file-name.csv'); // create a output file stream $output = fopen('php://output', 'w'); // output the column headings fputcsv($output, array('Table Column 1', 'Table Column 2', 'Table Column 3', 'Table Column 4')); $results = mysql_query('SELECT field1,field2,field3,field3 FROM table_name'); // loop over the rows, outputting them while ($results = mysql_fetch_assoc($results)) : fputcsv($output, $results); endwhile; ?> |
Found this useful? Share it with your friends. Thank you for giving time on freewebmentor community. Please don’t forget to subscribe our newsletter or join us on Facebook to be the first to learn the next great thing from freewebmentor.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: csv export example, csv export using mysql and php, export mysql data in .csv format, how to export mysql data, mysql export using php