PHP – Export MySQL to CSV

I would like to teach about exporting data as CSV in PHP. First, CSV is a file format called Comma Seperated Values. It can be opened using MS Excel or other similar spreadsheet software. Consider a scenario where, you have a large website and it has about 10,000 registered users. You would like to get the list of users who registered in the month of August 2013 to send them a mail, for an offer.

First create a PHP file, for database connection.

// Create connection
$file = fopen("email_ids.csv","w");
if (mysqli_connect_errno()) // Check connection
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
// Perform queries
$query_res = mysqli_query($con,"SELECT `email` FROM `user_details` WHERE `date` BETWEEN '08-01-2013' AND '08-31-2013'");
while ($row=mysqli_fetch_row($query_res))

Just you need to add two lines to your code. fopen(“email_ids.csv”,”w”); Which opens a file called “email_ids.csv” in write mode. And fputcsv($file,$row); which puts the array as each row into the csv file.

After successful execution of the php file, a new csv file will be created on the same location where php file is located.


Thanks for reading.

Follow me


Web Developer at Energy Alternatives India
I'm interested in developing Web applications andkeen on learning new technologies.

View Nagarajan's Profile
Follow me

Latest posts by Nagarajan (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *

займ на карту онлайн круглосуточно