Christian Little

Information on Everything!

PHP Code to Turn Any MySQL Query into a CSV File

By Christian Little • Nov 3rd, 2008 • Category: Web Development

Often times as a programmer I’m forced to use more creative solutions than are normally available. This typically applies to the case where somebody wants data from their database exported into a different program. Unfortunately, a lot of the time the standard mysql export feature isn’t an option (as they want to manipulate the data before it gets put into a file, or some other reason).

So here is the framework to do this:

$table = “sometable”;
define(”FILENAME”, “bob.csv”);
$fhandle = fopen(FILENAME, “w”);
$exportquery = “select * from $table”;
$header = “”;
$rows = “”;
$rowcounter = 0;
$exportresult = mysql_query($exportquery);
while($row = mysql_fetch_array($exportresult, MYSQL_ASSOC)) {
     $rows = “”;
     // Construct the Header row
     if(!$rowcounter) {
          $rowcounter++;
               foreach ($row as $key => $value) {
               $header .= ereg_replace(”,”, “”, $key) . “,”;
               }
          $header = rtrim($header, “,”);
          $header .= “\n”;
          fwrite($fhandle, $header);
     }

     // Construct a normal row
     foreach ($row as $key => $value) {
          $rows .= ereg_replace(”,”, “”, $value) . “,”;
     }
     $rows = rtrim($rows, “,”);
     $rows .= “\n”;
     fwrite($fhandle, $rows);
}
fclose($fhandle);

In a nutshell, this code will take all the data from any table in a MySQL database and export it to a CSV file. The cool thing about this code is that is uses associative arrays to parse the data, so it doesn’t matter what the field names are, it will always use the correct name.

If you take this code and simply change the $table variable and add your mysql_connect and mysql_select_db commands right at the top, it will dump the entire table for you in a fraction of a second to a file called bob.csv (which you can change on line 2 of the code to whatever name you want).

You can read through the code and figure it out if you want, but here is a basic logic charge for it:

  • Query the table, then for every row that is returned:
    • If this is the first row, then get the field names and create a header row to put at the top of the file.
    • Parse each field into the csv file accompanied by a comma
    • When an entire row has been parsed, it chops off the extra comma on the end of the row and replaces it with a newline character

It’s very straight forward logic, and works almost identically to the built-in export/dump functions.

The other nice part about this code is that it will work with very complex queries involving multiple joins. So you could do this:

$exportquery = “select
t1.id as ID,
t1.name as Name,
t2.Email as Email,
FROM $table t1
LEFT JOIN emails t2 ON t1.ID = t2.ID
LIMIT 100″

That query will work in this code, and it will output a CSV file with 100 rows of data containing ID, Name, and Email from 2 tables in your database. If you try to do this in MySQL directly with an export or dump command, it’s not as easy and simple.

Happy coding everybody!


Christian Little is a web monkey and owner of this website. Aside from blogging about webmastering, SEO, and marketing, he spends his time with his family, running too many websites, playing counter-strike, and provides SEO consulting for a few select clients around the world.
Email this author | All posts by Christian Little

11 Responses »

  1. Works great thanks. I couldn’t get the fputcsv($file,$line); to work.

    Rate this comment:
    2.5
  2. I’m not sure if you copied the code then properly Phil, as I don’t use that command. The code above uses just the standard fwrite, not fputcsv, so I can’t really provide much assistance on what you did wrong.

    Could you provide more detail on the problem?

    Rate this comment:
    2.5
  3. Thank you very much for the code…

    Rate this comment:
    2.5
  4. Great work buddy. Thanks for sharing.

    Rate this comment:
    2.5
  5. Hi Christian,

    I’ve been working with SQL on mainframes and servers since VM SQL/DS V2 ( a very long time). There has always been a need for importing or export data from SQL tables. It is not just CSV files but many more files structures are involved. Hence I have always taken the base route, that is creating formatted text files. I found that as a technique it gives the flexibility needed in large organisations. Although I am gladdened to see that at least someone is showing an inititive in the open source approach to data transfer.

    regards
    George

    Rate this comment:
    2.5
  6. I’ve done a lot of searching on google for this type of content. Glad I finally found this site! Great work.

    Rate this comment:
    2.5
  7. PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in standalone graphical applications.

    Rate this comment:
    2.5
  8. The cool thing about this code is that is uses associative arrays to parse the data.

    Rate this comment:
    2.5
  9. ????? ????? ???? ??? ???, ???? ????? ??? ?????? ??? ?? ????. ????? ?????. ? ?? ?? ???? ? ??? ?????? ???????

    Rate this comment:
    2.5
  10. Thanks for the script really i am looking for that.

    Rate this comment:
    2.5
  11. Wow really thanks for the code its really helpful. i am tired of searching this.

    Rate this comment:
    2.5

Leave a Reply