Export the database table as CSV format using PHP

Export the database table as CSV format using PHP

data-table-export
This code need some files those files are,
1.db.php
2.export.php
3.index.php
as in the db.php file, make this.

database name –> wallstreet
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('wallstreet', $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 "rn";
}
?>

INDEX.PHP
this file is just for do the 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>

Leave a Comment