A step-by-step guide to export data to CSV from MySQL using PHP
It is a basic task for any application that needs a reporting feature to CSV; here I am going to explain how to generate a CSV file from the MySQL records.
Let’s get started:
Table of Contents
Step 1 – Create Sample Database and Required Table along with the data:
Create Database table with sample records, here I am going to use a `users` table, which is going to have user’s details, go ahead and use following SQL statements to create table and insert the records. (Note: you can skip this step if you have your existing database tables)
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(40) NOT NULL, `last_name` varchar(40) NOT NULL, `email` varchar(50) NOT NULL, PRIMARY KEY (`id`) ); INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`) VALUES (1, 'Jerry', 'McKenny', 'firstname.lastname@example.org'), (2, 'Lillian', 'Evans', 'email@example.com'), (3, 'Eva', 'Osborne', 'firstname.lastname@example.org'), (4, 'Darlene', 'Edwards', 'email@example.com'), (5, 'Bill', 'White', 'firstname.lastname@example.org');
Step 2 Create PHP to MySQL Database Connection Script:
Create Database configuration file, which is going help us to connect to MySQL from PHP file.
Step 3 – Add Sample Index Page to List out the Records:
Create `index.php` file and list records.
Step 4- Exporting MySQL Data to CSV file PHP Script:
Create `export.php` file to export data from MySQL to CSV.
Click OK to export the data to CSV and your file gets downloaded
If you check download file, you get records listed, as showing below:
We are done, you can download the complete source for reference use following links to download or checkout live demo. Live Demo
Next you can learn how to import data from CSV to MySQL here – Import Data from CSV File to MySQL Using PHP