Create a CSV file using PHP/MYSQL

Sep 16, 2013, by admin

As we know that CSV files are one of the most used way to back-up mysql database and tables. However it is very simple to export or backup your mysql database table as CSV file if you have PhpMyAdmin interface installed on your server. Actually problem arises when we have to deal with a shared hosting. But by using PHP script, you can export complete mysql database table to csv files. Here in this post I have given you a simple PHP script to create a CSV file. The script will call the database and select a table. Then it downloads the content line by line in a csv file.

  1. <?php
  2. $DBHOST = ‘localhost’;
  3. $DBUSER = ‘root’;
  4. $DBPASS = ”;
  5. $DATABASE = ‘mytestdatabase’;
  6. $TABLE = ‘emp’;
  7. $FILE_NAME = ‘emp.csv’;
  8. $dblink = mysql_connect($DBHOST, $DBUSER, $DBPASS) or die(“Can not connect.” . mysql_error());
  9. mysql_select_db($DATABASE) or die(“Can not connect.”);
  10. $result = mysql_query(“SHOW COLUMNS FROM ”.$TABLE.“”);
  11. $i = 0;
  12. if (mysql_num_rows($result) > 0) {
  13. while ($row = mysql_fetch_assoc($result)) {
  14. $my_csv_output .= $row[‘Field’].“,”;
  15. $i++;}
  16. }
  17. $my_csv_output .= “n”;
  18. $values = mysql_query(“SELECT * FROM ”.$TABLE.“”);
  19. while ($rowr = mysql_fetch_row($values)) {
  20. for ($j=0;$j<$i;$j++) {
  21. $my_csv_output .= $rowr[$j].“, ”;
  22. }
  23. $my_csv_output .= “n”;
  24. }
  25. $FILE_NAME = $FILE_NAME.“_”.date(“d-m-Y_H-i”,time());
  26. header(“Content-type: application/vnd.ms-excel”);
  27. header(“Content-disposition: csv” . date(“Y-m-d”) . “.csv”);
  28. header( “Content-disposition: filename=”.$FILE_NAME.“.csv”);
  29. print $my_csv_output;
  30. exit;
  31. ?>