MySQL to CSV Export Example (mysql data export)

By Ralph Vugts on Nov 12, 2012

For a long time now I've been looking for a simple to use MySQL to CSV Export script. Every single MySQL data export example I found never quite worked properly or it never added the headings to the CSV file which was extremly annoying.

With a little help from this outstanding script (Parse to CSV PHP) I was able to build one that works extremly well on any MySQL database query. (Which is great if you just want to export a small database segment, most CSV export programs just grab the whole database table).

Basically it creates a 2D array of all the data that is pulled from your query so the Parse to CSV class can then output it to a CSV file.

Good luck, I hope this saves you some time.

Code Example Below:

//Visit for more info.
//Connect to Database and perform your select
$sql="SELECT * FROM `yourtable`";
//Get the column names to add to the head of the CSV file
$csvHeader = array();
$columns = mysql_num_fields($result);
for($i = 0; $i < $columns; $i++) {
    $csvHeader[] = mysql_field_name($result,$i);
# include parseCSV class.
# create new parseCSV object.
$csv = new parseCSV();
//Turn the SQL results into a 2D array
$DataArray = array();
while($row =  mysql_fetch_assoc($result)) {
    $DataArray[] = $row;
//$csvHeader = array('Car name', 'color');
$csv->output (true, 'data.csv', $DataArray, $csvHeader);

Ralph has been developing websites and systems for nearly 20 years. Passionate and curious, he’s an a-typical developer who understands how users interact with the systems he builds. He understands that systems need to be human-friendly. Ralph loves working in an industry that is constantly changing and disrupting itself.

Get in touch, We love to talk