Easily Export Data From MySQL to CSV File

We have already written about “importing a CSV file to MySQL“, I thought about writing a script to export data from MySQL to CSV file. Its really important for websites to generate reports and this script can be used to do the same. Many e-commerce websites, business directory websites, classified websites and other business websites need to generate reports regularly. Just write suitable SQL query and pass that query to this script and it will fetch all the data and write it to a CSV file which will be downloaded to your system.

export mysql to csv


Code for index.php:


$conn = mysql_connect( 'localhost', 'root', '12345' ) or die( mysql_error( ) );
mysql_select_db( 'database_name', $conn ) or die( mysql_error( $conn ) );

$result = mysql_query( 'SELECT * FROM table_name', $conn ) or die( mysql_error( $conn ) );

header( 'Content-Type: text/csv' ); // tell the browser to treat file as CSV
header( 'Content-Disposition: attachment;filename=export.csv' ); // tell browser to download a file in user's system with name export.csv

$row = mysql_fetch_assoc( $result ); // Get the column names
if ( $row )
outputcsv( array_keys( $row ) ); // It wil pass column names to outputcsv function

while ( $row )
outputcsv( $row );    // loop is used to fetch all the rows from table and pass them to outputcsv func
$row = mysql_fetch_assoc( $result );

function outputcsv( $fields )
$separator = '';
foreach ( $fields as $field )

echo $separator . $field;
$separator = ',';        // Separate values with a comma
echo "\r\n";     //Give a carriage return and new line space after each record

Just edit SQL query as per your requirement and you will get the desired result in export.csv. You can use this script to generate simple reports from your MySQL database.

About sanjeev

Dreamer, Blogger and Thinker. I love to help people in solving their problems. You can also join me HERE

Related posts:

5 Responses so far.

  1. Hi sanjeev,
    I appreciate your curiosity to help people.
    But why did u choose this way ?
    I can’t able to create new topic or post things ….

  2. Hi!

    Is there a way to left a copy of the csv file in the server side.
    I mean to keep a copy of every exported csv file in the webserver.


Comments are closed.