• Home
  • Shell
    • Emacs
    • Perl
    • screen
    • sed
  • Ubuntu
    • VNC
  • Web Development
    • Javascript
    • Joomla
    • MySQL
    • osTicket
  • Windows
    • Gimp

PHP> Export simple MySQL query to .csv file

Aug08
2011
Written by Scott Rowley

The following will allow you to export your mysql queries from mysql to a csv file that can be opened in several spreadsheet softwares. You may need to change the , (comma) to a ; (semi-colon) depending on your software.

A note for those of you using my osTicket Reports MOD: This is not what I’m using for that.

<?php
$host = 'localhost';
$user = 'userName';
$pass = 'password';
$db = 'databaseName';
$table = 'tableName';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
Posted in MySQL, PHP, Web Development - Tagged csv, dev, development, excel, export, file, libre, MySQL, office, open, php, web
« Media> Shoutcast ‘No such file or directory’
» osTicket> Alert Department on Ticket Transfer

14 Comments

  1. Miguel BR's Gravatar Miguel BR
    September 10, 2012 at 8:58 pm

    A recommendation: the $filename must contain quotes.
    http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1

    Some times when a filename is “test file.txt” some browsers get stuck in “test”, they miss the “file.txt” part, so the line must be
    header(“Content-disposition: filename=\””.$filename.”\”.csv”);

    • Scott Rowley's Gravatar Scott Rowley
      June 23, 2013 at 10:32 am

      True, but in this case there will never be a space because we’re specificallly naming the file export_aTimeStamp.csv, so there is never any space present.

  2. Doug's Gravatar Doug
    February 5, 2013 at 5:54 pm

    I do not see a purpose for

    $i++;

    in the first WHILE loop.

    How is $i being used?

    • Scott Rowley's Gravatar Scott Rowley
      February 6, 2013 at 11:31 am

      Good point. Perhaps it was code that I used initially but ended up not using. I’ll remove it. Thanks!

      • Iain Wooster's Gravatar Iain Wooster
        March 1, 2013 at 8:12 am

        the i++ is needed in the first loop to create the upper limit for the column for next loop to write out the data rows

        • Scott Rowley's Gravatar Scott Rowley
          March 1, 2013 at 4:02 pm

          Ahh, yes. I missed the other reference to $i

          Thanks Wooster, I’ve put the code back in! 😉

  3. David Kyle's Gravatar David Kyle
    June 19, 2013 at 3:45 am

    Hi there, It’s been a while since anybody has asked a question on this — hopefully you’re still fielding them!

    I’ve found this and find it really useful as I’m very, very foetal in my PHP development (and aim to remain that way).

    What would be the best way to restrict columns that are printed in the file, I’ve tried a couple of times to no avail. Once by adding a continue statement that hides certain fields and once by editing the show columns to only WHERE field IN as it worked in MySQL workbench…

    Thanks in advance!

    • Scott Rowley's Gravatar Scott Rowley
      July 7, 2013 at 10:03 pm

      I don’t have time to work on this right now but I would think that you are on the right track with using ‘continue’ in one or more spots.

  4. Ankur's Gravatar Ankur
    July 4, 2013 at 11:16 am

    when i am trying to generate csv file which contains more than 25k rows. it returns me blank file. But when i only pull 22000 i can see the data but not when i pull 25k or more …is it something needs to do in excel?

    • Scott Rowley's Gravatar Scott Rowley
      July 7, 2013 at 10:01 pm

      What is the size of the file when you have over 25k entries? Does it actually get filled or does the sql query simply fail out and the file is empty?

  5. Samrat Khan's Gravatar Samrat Khan
    August 22, 2013 at 4:31 am

    Firstly, Let me describe little. I have used this code to execute my CSV output. It is working fine. Problem that I have created a LEFT JOIN query. Data of that query working fine. But, Must I have to select table column. Otherwise, it is giving me the blank CSV file. How may I resolve the problem?

    • james's Gravatar james
      August 25, 2014 at 8:56 am

      create the sql as a view , then you can just refence that view and not worry about the outerjoin.

      let the database do the work , not your webserver.

      • Scott Rowley's Gravatar Scott Rowley
        August 26, 2014 at 2:26 pm

        Can you give an example? I don’t believe I’ve ever done anything with a “view”.

        Thanks for the comment!

  6. Colin Parkinson's Gravatar Colin Parkinson
    August 3, 2014 at 1:03 am

    Hi all — just looking/trying the code and it works ok — but how can I select columns from a table to export rather than the whole table. 🙂
    Any clues.
    Thanks

Corrections? Questions? Comments?

Find an error?
Everything work out great for you?
Have some feedback?
Like to see something added to the article?

PLEASE leave us a comment after the article and let us know how we are doing, or if something needs corrected, improved or clarified.

Thank you!
- The Management

Advertisement

Sudo Bash
By Geeks - For Geeks

Back to Top