Facebook Twitter Reset

This Tutorial Has Been Viewed 9,000 Times.

Export MySQL to CSV (Excel) using php

You can export your MySQL database to .csv file format (Microsoft Excel file) easily using php.

This tutorial require 1 PHP file and 1 table of mySQL database.

1. exportcsv.php
2. The table is with 2 fields: id(auto_increment), name(varchar, 50) and put some records about 20 – 30 records into this table. (directly by phpMyAdmin)
The exportcsv.php file looks like this :-

< ?php
// Connect database
$database="mydb";
$table="mytablename";
mysql_connect("localhost","","");
mysql_select_db("mydb");

$result=mysql_query("select * from $table");

$out = '';

// Get all fields names in table "mytablename" in database "mydb".
$fields = mysql_list_fields(mydb,$table);

// Count the table fields and put the value into $columns.
$columns = mysql_num_fields($fields);

// Put the name of all fields to $out.
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";

// Add all values in the table to $out.
while ($l = mysql_fetch_array($result)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}

// Open file export.csv.
$f = fopen ('export.csv','w');

// Put all values from $out to export.csv.
fputs($f, $out);
fclose($f);

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
?>

VN:F [1.9.13_1145]
Rating: 8.6/10 (14 votes cast)
VN:F [1.9.13_1145]
Rating: +3 (from 5 votes)
Export MySQL to CSV (Excel) using php, 8.6 out of 10 based on 14 ratings

Incoming search terms:




You will also be interested in ,

One Response to “Export MySQL to CSV (Excel) using php”

  1. Yas27
    January 20, 2012 at 9:50 pm #

    thank youuuuuuuuuuuuuuuuuuuu!!

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.13_1145]
    Rating: 0 (from 0 votes)

Leave a Comment

Spam protection by WP Captcha-Free

Affordable Seo PackagesSeo BlogEdu Backlinks
More in Wordpress Tips (1 of 10 articles)