Create a CSV file using PHP and MYSQL

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 using PHP and MYSQL. The script will call the database and select a table. Then it downloads the content line by line in a csv file.


    $DBHOST = ‘localhost’;
    $DBUSER = ‘root’;
    $DBPASS = ”;
    $DATABASE = ‘mytestdatabase’;
    $TABLE = ‘emp’;
    $FILE_NAME = ‘emp.csv’;
    $dblink = mysql_connect($DBHOST, $DBUSER, $DBPASS) or die(“Can not connect.” . mysql_error());
    mysql_select_db($DATABASE) or die(“Can not connect.”);
    $result = mysql_query(“SHOW COLUMNS FROM ”.$TABLE.“”);
    $i = 0;
    if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
    $my_csv_output .= $row['Field'].“,”;
    $my_csv_output .= “n”;
    $values = mysql_query(“SELECT * FROM ”.$TABLE.“”);
    while ($rowr = mysql_fetch_row($values)) {
    for ($j=0;$j<$i;$j++) {
    $my_csv_output .= $rowr[$j].“, ”;
    $my_csv_output .= “n”;
    $FILE_NAME = $FILE_NAME.“_”.date(“d-m-Y_H-i”,time());
    header(“Content-type: application/vnd.ms-excel”);
    header(“Content-disposition: csv” . date(“Y-m-d”) . “.csv”);
    header( “Content-disposition: filename=”.$FILE_NAME.“.csv”);
    print $my_csv_output;

This is a tested script just copy and paste it to your server.


Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *