Thursday, 17 July 2014

Export the MySQL database table as CSV format using PHP

Export the database as in the configuration of CSV to open it in the Microsoft office (MS)-Excel. Most the social networking sites and E-commerce site and more destinations or this sort of database fare coding for without going to administrator board, simply in a single click fare the database table as in the organization of CSV to open it in MS-Excel. Simply on a click export the database table, utilizing PHP code. Let perceive how it functions.

This operation requires some PHP code and header code make the operation fruitful from the program, which is the reason we need to utilize the header code within this. Furthermore this code require a few records those documents are
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

And as you, here i just declare what I have given in.

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
This file is only for do the download; simply give the link anchor tag, typically you know to make simply click export the data, for that simply give the connection on anchor link, that will send out the information table.
<a href="export.php"> export the database table </a>

As given in the above line. Just do it as I mentioned the above.

No comments:

Post a Comment