Exporting MySQL Data To CSV In PHP

Do you want to export data stored in a MySQL database to CSV file?

The solution is damn easy if you already know how to connect to MySQL database and read or display data from a PHP script. Let's start working on it.

Let us first create a sample table. In our example scenario, let us create a table to store contact information.

CREATE TABLE `contacts` (
`first_name` VARCHAR( 50 ) NOT NULL ,
`middle_name` VARCHAR( 50 ) NOT NULL ,
`last_name` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 320 ) NOT NULL ,
`phone` VARCHAR( 20 ) NOT NULL
) ENGINE = MYISAM;

In our MySQL database table 'contact' we store first name, middle name, last name, email address and phone number. Time to insert sample data to our table.

INSERT INTO `contacts` (
`first_name` ,
`middle_name`,
`last_name`,
`email`,
`phone`
)
VALUES 
('Brendan','Deleon','Thane','egestas.Sed@convallisest.ca','1-668-404-1712'),
('Thaddeus','Herrera','Upton','pede@purussapiengravida.ca','1-813-414-5014'),
('Kibo','Mcintosh','Chester','neque@interdum.com','1-570-799-1809'),
('Palmer','Branch','Reuben','diam.luctus@Morbi.com','1-743-889-4016'),
('Cain','Price','Timothy','felis.orci.adipiscing@faucibuslectusa.com','1-952-159-0353'),
('Jasper','Hebert','Noah','Phasellus@consectetuer.ca','1-148-209-9963');

We just inserted 6 records to our contacts table.

Time to write the PHP script. Let's do it step by step to understand the process better.

Step 1: Establish connection to database server and select the database.


<?php
$link 
mysql_connect('localhost''my_db_user''myPassword');
mysql_select_db("my_db");
?>

Step 2: Query the database and store the result in $result.

<?php
$result 
mysql_query('SELECT * FROM contacts');
?>

Step 3: We accumulate the contents of CSV in the variable $file. We set it to null value to make sure it is empty. We fetch the data from the query result and loop through the rows. After each column value is appended to $line, we also append the ','. We separate the values by comma. At the end of each line we append the newline character. The PHP constant PHP_EOL makes our script cross platform compatible. Once the control comes out of our loops, the CSV content is stored in $file.

<?php
$file 
'';
while (
$row mysql_fetch_array($resultMYSQL_NUM)) {
    
$line '';  
    foreach (
$row as $value) {
        
$line .= $value ',';
    }    
    
$file .=  $line PHP_EOL;    
}

?>

Step 4: We set the appropriate HTTP headers. The 'Content-Type' header indicates that the data is in CSV format. The 'Content-disposition' header indicates to the browser that the data has to be offered as a file download. Once we set the headers, we just echo our $file variable which contains the CSV data.

<?php
header
('Content-Type: application/csv'); 
header('Content-disposition: attachment; filename=my_csv.csv');
echo 
$file;
?>

About the author

Sudheer is an entrepreneur and software developer. Get more from Sudheer on Twitter.


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.