• How to Export CSV File Data from Mysql Using PHP

    In this tutorial, I will explain how you can export CSV data from your database. Following code should help beginner level PHP/Mysql developers who are looking for an easy way to export a CSV file from a Mysql database.

    Let’s understand this from the start:

    SQL query to create “Contacts” table in PhpMyAdmin:

    CREATE TABLE IF NOT EXISTS `contacts` (

    `ID` int(10) NOT NULL AUTO_INCREMENT,

    `name` varchar(50) NOT NULL,

    `email` varchar(50) NOT NULL,

    PRIMARY KEY (`ID`)

    )

    Code For export_csv.php:

    <?php

    mysql_connect(“hostname”,”user”,”password”);

    mysql_select_db(“databasename”);

     

    $fp = fopen(“test.csv”, “w”);

     

    $res = mysql_query(“SELECT * FROM contacts”);

     

    // fetch a row and write the column names out to the file

    $row = mysql_fetch_assoc($res);

    $line = “”;

    $comma = “”;

    foreach($row as $name => $value) {

    $line .= $comma . ‘”‘ . str_replace(‘”‘, ‘”"‘, $name) . ‘”‘;

    $comma = “,”;

    }

    $line .= “\n”;

    fputs($fp, $line);

     

    // remove the result pointer back to the start

    mysql_data_seek($res, 0);

     

    // and loop through the actual data

    while($row = mysql_fetch_assoc($res)) {

    $line = “”;

    $comma = “”;

    foreach($row as $value) {

    $line .= $comma . ‘”‘ . str_replace(‘”‘, ‘”"‘, $value) . ‘”‘;

    $comma = “,”;

    }

    $line .= “\n”;

    fputs($fp, $line);

    }

    fclose($fp);

    echo “CSV file successfully created !!”;

    ?>

    Please make sure the table is already created before trying to export the data.

    Kindly post your report if you find any bugs.

Comments on this post

Leave a Reply

  • Security Code :


    5 × = twenty