Thursday, November 20, 2014

Export MySQL Database Table as CSV Format in PHP

We know that, most of the social media and e-commerce sites export coding without going into the admin panel with just one-click of export the database tables as in the format of CSV to open it in MS-Excel. Just on a click export the database table, using PHP code. Let see how it works.

               DOWNLOAD                                                            LIVE DEMO

This operation needs some PHP code and header code to make the operation successful from the browser. Below is the list of necessary files.

  1. db.php
  2. export.php
  3. index.php
as in the db.php file, make this.

database name --> 2my4edge
table name--> export_table
column names --> id,name,place

DB.PHP

<?php
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db=mysql_select_db('2my4edge', $conn) or die(mysql_error());
?>

EXPORT.PHP

<?php
include('db.php');

//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');

//select table to export the data
$select_table=mysql_query('select * from export_table');
$rows = mysql_fetch_assoc($select_table);

if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysql_fetch_assoc($select_table);
}

// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';

// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('', $field_name) . '';
}
echo $separate . $field_name;

//sepearte with the comma
$separate = ',';
}

//make new row and line
echo "\r\n";
}
?>

INDEX.PHP

Index.php file is just use to download, just give the link anchor tag, usually you know to make just click export the data, for that just give the link on anchor link, that will export the data table.

<a href="export.php"> export the database table </a>

0 comments:

Post a Comment