PHP simple : PHP tutorial, MySQL tutorial
PHP Tutorial - Free PHP Script

Home | Tutorials | Php vs Node.Js | Web Tools

Export MySQL to CSV (Excel)

Tutorials > Export MySQL to CSV (Excel)

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

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

  1. export_csv.php
  2. Database "tutorial" and table "name_list" with 2 fields: id(auto_increment), name(varchar, 50) and put some records about 20 - 30 records into this table. (directly by phpMyAdmin)


page navigator

Source Code

// Connect database

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

$out = '';

// Get all fields names in table "name_list" in database "tutorial".

$fields = mysql_list_fields(tutorial,$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);

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


Put Ebay RSS Feeds onto your website
SEO Elite Software
Domain Dashboard CPanel & Seo Manager
Work at Home Ideas and Opportunities
Introduction & Get Start
Using Form
PHP Tags
PHP Variables
PHP Control Structures
Create Database & Table
Database Connection
Insert Record
Select Record
Update Record
Delete Record
[email protected]