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

                                   [button_round color=”blue” url=”infotuts.com/demo/export-mysql-csv/download.html”] DOWNLOAD [/button_round]

Code for index.php:

    <?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.


Posted

in

, ,

by

Tags:

Comments

5 responses to “Easily Export Data From MySQL to CSV File”

  1. venkatesh K Avatar
    venkatesh K

    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. Josh Harwood Avatar
    Josh Harwood

    Hi, i think this is missing a closing ‘}’ for the while statement

  3. bozape Avatar

    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.

    Thanks!

  4. Vipin Avatar
    Vipin

    Getting Error with this code……..
    Error——-> call to undefined function outputcsv

  5. hamood alazri Avatar

    Hi, i think this is missing a closing ‘}’ for the while statement inline 21