Exporting a table into csv file
Today I was working on a website, and I came into this situation where I had to export all the entries in the database into a csv file. So in this post, I am going to explain how I did this. If you are using CodeIgniter then you should better check out http://writephp.blogspot.com/2013/02/export-to-csv-ci-helper-file.html where I have written how the simple CodeIgniter helper file can be used. But if you want to do using some hard core php then you should try this out. Here's the sample code:
<?php
$table='tablename';
$DB_HOST = "host_name";
$DB_USER = "db_username";
$DB_PASS = "db_pass";
$DB_NAME = "databasename";
$con=mysql_connect($DB_HOST,$DB_USER,$DB_PASS);
if(!$con){
die('Database connection failed:'.mysql_error());
}
$db=mysql_select_db($DB_NAME,$con);
if(!$db){
die('Database selection failed'.mysql_error());
}
$fp=fopen($table.'.csv','w');
$sql0="explain $table"; $res=mysql_query($sql0,$con); $header=array();
while($row=mysql_fetch_array($res)){
array_push($header,$row[0]); }
fputcsv($fp,$header);
$sql="SELECT * FROM `$table` ORDER BY `$table`.`dates` ASC";
$res=mysql_query($sql,$con);
while($row=mysql_fetch_assoc($res)){ fputcsv($fp, $row);
}
fclose($fp);
?>
Once you run the script with appropriate values for $table,$DB_HOST,$DB_USER,$DB_PASS,$DB_NAME, a file will be create with the name of the table you provided. This way you can export a table into a csv file. If you are want to improve this code then go ahead. Possibly first thing you would like to do is place it in a library file. You can do the way you want. Just don't use this way for your real projects.
Comments
Post a Comment