PHP coding for download database to CSV format

This is download database  in  CSV format.why we are  use this ? if  database can  be corrupted . you can use the  download and  import easy to database.



Coding for  view Database Value


<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Export</title>
<style type="text/css">
p{padding:0;margin:0;}
.nav{width:80%;margin:0 auto;font-family:Arial;}
.table{width:40%;margin:0 auto;}
</style>
</head>
<body>
<div class="nav">
<h2><a href="http://crackerworld.blogspot.in/">Cracker World</a></h2>
<div class="table">
<p align="right"><a href="download.php">Download CSV</a></p>
<table border="1" cellspacing="0" cellpadding="0" width="100%">
<tr bgcolor="#306161">
<th width="12%" scope="col">S.No</th>
<th width="26%" scope="col">Reg NO</th>
<th width="41%" scope="col">Name</th>
<th width="21%" scope="col">Dept</th>
</tr>
<?php
$conn=mysql_connect('localhost','root','');
$selectdb=mysql_select_db('demo',$conn);
$sql = mysql_query("select * from employee");
$i=1;
while ($row = mysql_fetch_array($sql)) {
$reg_no=$row['reg_no'];
$name=$row['name'];
$dept=$row['dept'];
?>
<tr align="center">
<td><?php echo $i++?></td>
<td><?php echo $reg_no;?></td>
<td><?php echo $name;?></td>
<td><?php echo $dept;?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
</body>
</html>

Coding for download CSV


<?php
$conn=mysql_connect('localhost','root','');
$selectdb=mysql_select_db('demo',$conn);
$select_db = mysql_query("select * from employee");
$columns_total = mysql_num_fields($select_db);
while ($rows = mysql_fetch_array($select_db)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$rows["$i"].'",';
}
$output .="\n";
}
$save_filename = "employee.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$save_filename);
echo $output;
exit;
?>

No comments:

Post a Comment