Export Mysql data to CSV – PHP tutorial

Written by Gertjan on December 16th, 2007

Want to export your Mysql data to a CSV(comma seperated value) file? In this tutorial i will show you how to export your data from Mysql into a CSV file.

Fist off we start by creating the connection to the Mysql database:

  • $host: this is the location for the Mysql server it can be a hostname or an ip adress. it is usualy localhost.
  • $db: this is the Mysql user account used to access the database.
  • $user: this is the password for the Mysql user account
  • $pass: this is the name of the Mysql database used.

Now we include the export function.

We will need to include the function ‘exportMysqlToCsv‘ in the file ‘exportcsv.inc.php‘

Now we declare what table should be exported from Mysql into the CSV file:

  • $table: The name of the table that should be exported from Mysql to csv.

Now we start the export to csv from mysql by calling the function ‘exportMysqlToCsv‘:

This function will export all data in the Mysql table. It will place the fieldnames on the first row of the CSV file.
The function will export all Mysql data to a file called ‘export.csv’ by default.
You can change this by adding an extra parameter to the exportMysqlToCsv: exportMysqlToCsv($tablename,$filename).
When the export finishes all your data will be inserted into the csv file and the file will be presented as a download.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
 
$host = 'localhost'; // MYSQL database host adress
$db = ''; // MYSQL database name
$user = ''; // Mysql Datbase user
$pass = ''; // Mysql Datbase password
 
// Connect to the database
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
 
require 'exportcsv.inc.php';
 
$table=""; // this is the tablename that you want to export to csv from mysql.
 
exportMysqlToCsv($table);
 
?>

The actual Mysql Export to csv function:

Feel free to alter this file to your needs:

To change the default filename of the exported data change the $filename variable to your likings.

file: exportcsv.inc.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
 
function exportMysqlToCsv($table,$filename = 'export.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    $sql_query = "select * from $table";
 
    // Gets the data from the database
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);
 
 
    $schema_insert = '';
 
    for ($i = 0; $i < $fields_cnt; $i++)
    {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for
 
    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;
 
    // Format the data
    while ($row = mysql_fetch_array($result))
    {
        $schema_insert = '';
        for ($j = 0; $j < $fields_cnt; $j++)
        {
            if ($row[$j] == '0' || $row[$j] != '')
            {
 
                if ($csv_enclosed == '')
                {
                    $schema_insert .= $row[$j];
                } else
                {
                    $schema_insert .= $csv_enclosed . 
					str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                }
            } else
            {
                $schema_insert .= '';
            }
 
            if ($j < $fields_cnt - 1)
            {
                $schema_insert .= $csv_separator;
            }
        } // end for
 
        $out .= $schema_insert;
        $out .= $csv_terminated;
    } // end while
 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($out));
    // Output to browser with appropriate mime type, you choose ;)
    header("Content-type: text/x-csv");
    //header("Content-type: text/csv");
    //header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=$filename");
    echo $out;
    exit;
 
}
 
?>

Tags: , , , , , , ,

Related Posts:

131 Responses to “Export Mysql data to CSV – PHP tutorial”

  1. raymonn Says:

    tnx… this is really useful

  2. Jay Says:

    Very handy,

    Is there a method to concatenate particular row data (denoted by a unique identifier) from several tables into one CSV file?

    Thanx

  3. Bernard Says:

    Thanks for this great info! Is there a way to save the .csv file to your server after export, and not have it as a download? Or is it done already?

  4. Stevet540 Says:

    Hi, new to PHP so not too sure what i am doing. Script works great, and just what i need but i would like to change the field headings to match outlook 2007. I am using 2 fields, currently ‘username’ and ‘e-mail’, and would like to name them ‘First Name’ and ‘E-mail Address’. Have tried for hours now and can’t figure it out. Help please.

  5. naughty Says:

    is there any way to bold the title of exported CSV file. Kind Regards, Naughty

  6. Fred Says:

    I might be wrong, as I only had a quick look at the code. You can expand this function by passing the function a query in stead of a table. This should enable you to pass it a join query and thus join multiple tables (Jay).

    You can then also use the ‘as’ identifier to rename the fields (Stevet540)

    If you want to know how, just replace the line
    $sql_query = “select * from $table”;
    with
    $sql_query = $table;
    and then pass the query when calling the function:
    exportMysqlToCsv(“select * from some_table”);

    This is not neat, or good code, but should work.

    Thanks for the tut. I found it very useful.

  7. Praveena Says:

    Thank u very much ,It’s very useful for me.

  8. Rishi Says:

    Thanks for this Great Code!

  9. Paul Says:

    Perfect. Excellent, simple solution.

    Rather than require the other file, I just combined the two php files into one. Any problems with that?

  10. Neetu Says:

    I want to this csv file as email attachment to mail on single address.
    Plz hlp me. Send me code on my email as soon as possible.

  11. shivaganesh Says:

    good stuff! thanks a lot..

  12. shivaganesh Says:

    Nice function. Thanks a lot

  13. jms Says:

    i’m trying to use your script here; looks to be pretty solid. however, i’m encountering some issuesw/ the headers…any help would be appreciated…i’m still a noob.

  14. Bảo Trân Says:

    Thanks a lot . It’s useful for me :-)

  15. jms Says:

    so, i left a comment about how i was having problems w/ the headers.
    (don’t see it here)

    people may run into the same issue i did (noob-sauce for reals) but here’s a tutorial/explaination for what was happening.

    http://www.kirupa.com/forum/showpost.php?p=2149084&postcount=3

    with the script provided here (awesome, btw) and that tutorial, you have everything (as a noob) to get this export to csv going. cheers.

  16. Piya Says:

    Hiii …
    This is very nice n useful code..
    but I actually want to store file on localhost after exporting ..
    can u tell me wht can I do for it??

    Thanks in advance

  17. nard Says:

    what if i want to export only some fields from the table?

  18. Neetu Says:

    plz help me to attach csv file in as emailattachment to send on specified email address only.

  19. tech Says:

    Nard, if you want to export some fields, replace the line

    $sql_query = “select * from $table”;

    with

    $sql_query = “select id, Name, Email from $table”;

    (where id, Name, Email are require fields)

  20. nard Says:

    thank you very much tech! solved my problem.

  21. Tiaan Says:

    I am having some problems:
    At first I had a problem with my database connection so the .csv download was presented but no data was in it.
    I have since fixed the connection string but now the data is just dumped into the browser instead of providing me with the download.
    Can someone please help!

  22. Ranvir Says:

    Thanks a lot for the post!! Really helped me.

  23. Casey Wise Says:

    Very nice! Thanks for taking the time to put this up!

  24. Memo457 Says:

    Greetings, Thank you so much for the scripts. I have been working for weeks trying to figure out how to get the array to work and then make it where it would take the CSV and place the field names at the top with seperators. If whoever created it were standing right next to me they would have a whopper from BK sitting on their desk for lunch and a big hug to boot. Thanks again.

  25. tulika Says:

    if i want to add some value in action of this file
    than what can i do

    this not work properly by me
    for example id of table in query

  26. Joseph Says:

    There is a issue with microsoft explorer downloading files from
    a site using SSL (secure socket layer). In order to get it to work
    you must add this additional header:

    Header(‘Pragma: public’);

  27. JuJuBean Says:

    This just dumps to the browser display – no prompt for filesave or anything.

  28. likki Says:

    thanks for that code. is there any way to format the cell in csv(ex. from numeric to text)

  29. krishna raya Says:

    Thanks a ton!! it was very useful

  30. CC Says:

    How do you export text fields which contain blank lines?
    When exporting in windows (IIS), the blank lines are converted into a funny symbol.
    Thanks

  31. Laura Says:

    Can anyone explain how to save the file on the server instead of downloading?? Please help!!

    thanks…

  32. MC@llivon Says:

    wow its great thank you very much

  33. sagar Says:

    thank u very much but how can we export multiple table data into bone excel sheet

  34. saneesh k Says:

    i have tested the code available in this site..iam using php code..so how to implement this code
    for getting the output form of the data that has been stored in the database..that is the whole datastored in the perticular table….

  35. ashish saxena(chandigarh,india) Says:

    Thanks a ton!! it is very useful.but i have a problem ,i want to export
    all tables with data into bone execl sheet.any one can help me??
    Thanks

  36. ASHISH SAXENA (CHANDIGARH) Says:

    Thanks a ton!! it IS very useful.i have a problem,how can we export multiple table data into bone excel sheet.any one can help me.
    Thanks

  37. Catherine Pope Says:

    Thank you so much for this excellent tutorial – you’ve just made my day much easier!

  38. Salim Says:

    Hey

    Finally i got something to cheer,I was searching the net for 2 hours and i was getting all crap of code snippets.

    This works fine for me,and very happy now after two hours of search

    thanks a lot
    Finally i can relax a bit
    thanks again

  39. Jim Hall Says:

    THANK YOU, THANK YOU!

    This was what I was looking for. Downloaded, insterted my db info and I had the “backup” file I needed inless than 15 mis.

    Again, Thank You

  40. Louis Goyard Says:

    LAURA SAID:
    “Can anyone explain how to save the file on the server instead of downloading?? Please help!!”

    Hi Laura,

    You have to write to the disk instead of sending info to the browser. What you need to do is to forget about all the commands HEADER(blabla). Take all those off the script. Instead, white the following:

    if (!$handle = fopen(‘filename.ext’, ‘x’)) {
    echo “Cannot open/create filename.ext”;
    exit;
    }
    if (fwrite($handle, $out) === FALSE) {
    echo “Cannot write to filename.ext”;
    exit;
    }
    echo “Success!”;
    fclose($handle);

    Watch that the $OUT variable used in fwrite() is the CSV data produced by the exportMysqlToCsv() above…

  41. Michael Says:

    Hello, very good and working code. Im new to that kind of code so forgive me.

    I have 3 diferent tables

    players:
    id_player
    name_player

    players_details:
    id_player
    position
    age

    players_eval:
    id_player
    value
    wage

    You can see that the ‘id_player’ is in all players. Now, what i want to do is export on csv and if the ‘id_player’ is the same number with the other tables to continew and show the rest of the info i have on the mysql

    Thank you

  42. Nuwan Says:

    Thank you so much,
    This was really useful!

  43. Cam D Says:

    woot woot! That was so simple, you saved me hours! Much appreciation!

  44. Jason Says:

    Thank you so much!!

    I have a problem about the export function.
    I am using UTF-8 coding for programming.
    I tried to export the CSV, and open by EXCEL directly, but I can not see the Chinese word.
    I need to open the excel first, then import external data and choose the Unicode coding.

    Any method let me more easily open the CSV?
    (simply double click to open)

  45. Export Mysql data to CSV - Tutorial Collection Says:

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 7:39 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  46. Krishna Says:

    When i used the above code i got the text below in the export.csv file, whats the matter…

    http://www.prizeitem.com:: Administration Console

    function s

  47. Bharat Says:

    Hi!

    Very useful tutorial for me.

  48. Joe Johnson Says:

    Great tutorial! I was able to get it working with just the addition of my MySQL information.

    One question – my csv export has some field data that seems to have ‘wrapped’ onto the next field — the table I am querying has over 110 fields. I can export in PHPMyAdmin and the data does not wrap.

    Is there somewhere in the above code I can set a file length?

  49. Joe Johnson Says:

    Regarding Post #47 – the issue is data related – text fields that have special characters entered like \@”.

  50. Salman Says:

    PHP 5 now has fputcsv function that was missing in 4.x releases of PHP. This function should take care of most of the conversion/parsing.

    http://www.php.net/fputcsv

  51. cestbibi Says:

    Thank you so much, I’ve been through lots of crappy scripts out there before finding your. Works just fine !!

  52. Larry Says:

    Wonderful. Thank you so much for taking the time to post and explain the script.

  53. Stephan Says:

    Great script it works perfect, I only have 1 question, how can I make the column names Bold.

    Thanks

  54. Marc Says:

    Is there a was to specify custom field names for the export?

    Example the field name in the db is ‘order_number’ and I would like the export field name to be ‘Order Num’

    Thanks

  55. Rupesh Says:

    mind blowing, i have been searching for this for so long. internet is alive because you people like you Gertjan

  56. Freaky Says:

    Bold? There is no text formatting in CSV it’s PLAIN text.

  57. masu Says:

    Thankx for the great script. I have one question, how can i write the contents to a file and save it automatically to a disk?

  58. JT Says:

    By default the script gets all fields in the table. I wanted to limit what fields where returned. Also, I wanted to have custom field names. This approach achieves both.

    Created array $fields_limit. This array holds the field names you want to include in the export and their custom names. Added parameter to function.

    $fields_limit = array(
    ‘first_name’ => ‘First Name’,
    ‘url’ => ‘Website’
    );

    exportMysqlToCsv($table,$filename,$fields_limit);

    You will need to modify exportcsv.inc.php:

    function exportMysqlToCsv($table,$filename = ‘export.csv’,$fields_limit=array())
    {
    $csv_terminated = “\n”;
    $csv_separator = “,”;
    $csv_enclosed = ‘”‘;
    $csv_escaped = “\\”;
    $fields = ”;
    if (count($fields_limit) > 0) {
    foreach ($fields_limit as $field => $format) {
    $fields .= $field . ‘, ‘;
    }
    $fields = substr($fields, 0, -2); // strip trailing comma
    $sql_query = “select {$fields} from $table”;
    } else {
    $sql_query = “select * from $table”;
    }

    To get custom field names:

    for ($i = 0; $i < $fields_cnt; $i++)
    {
    $field_name = stripslashes(mysql_field_name($result, $i));
    $format_field_name = $fields_limit[$field_name];
    $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
    $format_field_name) . $csv_enclosed;
    $schema_insert .= $l;
    $schema_insert .= $csv_separator;
    } // end for

  59. Tomo Says:

    Hi, great script.

    Is there a way assign a default directory where the file will be saved automatically? meaning without asking the user to save the file where ever they like.

  60. Andre Castillo Says:

    WOW! Worked like a stinking charm. Awesome, thanks!

  61. kaizer Says:

    Thank you! Just what I was looking for!

  62. jovani wayne Says:

    This looks great. Nice and simple script and nice explanations too. thanks for posting this tutorial!

  63. Rups Says:

    Great script! Is it possible to only export the records without the fieldnames?

  64. Patrice Fiset Says:

    Great script, save me time, thanks a lot.

  65. Danie Says:

    Hi,

    Script seems to work, but I get the following error:
    Warning: Cannot add header information – headers already sent by…

    I tried different solutions without luck

    Pleeeeze help!!

  66. H Burke Says:

    Great work! This is exactly what I needed.

  67. Roark Says:

    Hi Gertjan,

    The script works great, thanks a ton.

    Just wanted to know why you use the following conditional;
    if ($csv_enclosed == ”) {
    $schema_insert .= $row[$j];
    }else {
    $schema_insert .= $csv_enclosed . str_replace($csv_enclosed,$csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
    }
    $csv_enclosed == ” will always return false as $csv_enclosed is set in the begining and never closed?

    I’m just interested.
    Thanks
    Roark

  68. Roark Says:

    Aplologies, set in the begining and never CHANGED

  69. Vatsal Says:

    gr8 script..working perfectly

  70. yoav Says:

    great, thanks a lot!

  71. Batotoy Bitz Says:

    Is it possible to export the selected rows? by using checkbox? anyone…??

  72. jaspreet Says:

    Hi,

    Script seems to work, but I get the following error:
    Warning: Cannot add header information – headers already sent by…

    I tried different solutions without luck

    Pleeeeze help!!
    where is the solution?????

  73. Gertjan Says:

    Hi guys,

    i found some time to post some replies, so here goes:

    the header already send error:

    This happens when you copy and paste the script from here and leave in some extra whitespace before the tags

    Also if you’re using this script in other script, the PHP header() function cannot be called after output has already been given to the browser, it has to be called BEFORE, or use output buffering.

    so

    test

    will produce this error. as the HTTP header MUST be send before outputting something to the browser.

    @roark

    Good observation, it’s a little leftover code from the switch to spaghetticode to function, it can be removed as the variables are set in the top of the function.

    @ batotoy

    Not sure what you mean by the selected row and a combo box,

    but you can redefine the query with a where clause to narrow your export rows.

    something like this: $query = “select * from $table where id < 50" would export all rows where the ID column is less then 50

    Hope this helps
    greetz

  74. Ash Glover Says:

    Hi there,

    excellent tutorial, works like a charm.

    one item i’m a bit fuzzy on – the function declaration…

    function exportMysqlToCsv($table,$filename=’file.csv’) {

    i’m not familiar with the variable being specified and given a value in the declaration – ie, $filename=’file.csv’.

    i’m trying to customize the filename somewhat, with the date, but this doesn’t work, it seems – all i get is a file called “$filenamed”. any ideas on how to make this work?

    $filenamed = “webentries” . date(Ymj_hi) . “.csv”;
    function exportMysqlToCsv($table,$filename=’$filenamed’) {

    i have tried with and without the ‘ quotes, but without, i get a message about an unexpected T_VARIABLE.

    is there another way to specify this file name perhaps?

  75. Juha Says:

    Hi,

    This script is great. Is there possibility to export only those rows to .csv that fullfill some conditional expectation?

    For example if there are column which tells if some rows are accepted by someone somewhere and the value of those cells in that column are changed 1 (for example) and those which are not accepted are 0. Then i would want to export only those who are accepted (cell value = 1).

  76. Juha Says:

    Also another question which is bothering me. Is it possible make two different sqlquery which are then written to .csv files so that first querys first row is first row in .csv and second will be from second query (first row of that query) and third is again secod row of the first query and so on?

  77. tamilarasan Says:

    g8 work.. thanks a lot… how can i get all the tables records from database?

  78. Azis Says:

    HELP……. PLEASE……
    Ii want to export my data from mysql, and this is the case
    1. i have table called PO_BBD, then the structure like this

    msisdn varchar, calltime=varchar, calldate=varchar and charger = int

    | msisdn | calltime | calldate | charger|
    ———————————————————–
    | 005744 | 01:12:00 | 02JAN2010 | 125 |
    | 005744 | 12:12:20 | 04JAN2010 | 1 |
    | 005744 | 02:10:15 | 10JAN2010 | 125 |
    | 001212 | 09:22:15 | 01JAN2010 | 1 |
    | 001212 | 10:12:02 | 11JAN2010 | 300 |
    ———————————————————–
    thats my example data, i have 300 record. every msisdn have +- 30 record
    my questions

    1. how can i export to csv with condition every msisdn have its record
    2. i want otomatically loading and save, like this
    05744.csv
    001212.csv
    and if i open that file(05744.csv or 001212.csv) in notepad i want like this

    msisdn calltime calldate charger
    “005744″,”01:12:00″,”02JAN2010″, 125
    “005744″,”12:12:20″, “04JAN2010″, 1

    Please…… Help me…………..

  79. Azis Says:

    HELP……. PLEASE……
    I want to export my data from mysql, and this is the case
    1. i have table called PO_BBD, then the structure like this

    msisdn varchar, calltime=varchar, calldate=varchar and charger = int

    | msisdn | calltime | calldate | charger|
    ———————————————————–
    | 005744 | 01:12:00 | 02JAN2010 | 125 |
    | 005744 | 12:12:20 | 04JAN2010 | 1 |
    | 005744 | 02:10:15 | 10JAN2010 | 125 |
    | 001212 | 09:22:15 | 01JAN2010 | 1 |
    | 001212 | 10:12:02 | 11JAN2010 | 300 |
    ———————————————————–
    thats my example data, i have 300 record. every msisdn have +- 30 record
    my questions

    1. how can i export to csv with condition every msisdn have its record
    2. i want otomatically loading and save, like this
    005744.csv
    001212.csv
    and if i open that file(005744.csv or 001212.csv) in notepad i want like this

    “msisdn”,”calltime”,”calldate”,”charger”
    “005744″,”01:12:00″,”02JAN2010″, 125
    “005744″,”12:12:20″, “04JAN2010″, 1

    Please…… Help me…………..

  80. Blake Says:

    @Tomo

    Can you provide a plain text version of this code in its entirety? I would greatly appreciate it. There seems to be problems with copy/pasting this. Thanks.

  81. Wensi Says:

    I have a problem using this code….the web can show me the output…but i cannot find any csv file…/.\

  82. Tom Carnevale Says:

    A great little script and much appreciated.

    Can easily be enhanced by including prompts for the database and table.

    A genuine utility.

  83. danny Says:

    Great script it gives me the output, but the files is not saved. Of course like always, I am the only one, please help

  84. juan Velandia Says:

    A great little script and much appreciated, I’ll try to make it work on my website

  85. Kuldeep Says:

    Thank you.

  86. Superguyent Says:

    Is there a way that I can export images that are stored in the database to show on the spreadsheet. Each one of our products has a color code and I would like to be able to pull that color code image from the database and have it show beside the product on the spreadsheet.

    Thank You

  87. Tdude Says:

    OOOHHHH!
    What a relief. With newbie skills I’ve been trying to clean up and export stuff. Thanx to you Gertjan, my weekend is saved!
    *RESPECT*

  88. dewa Says:

    good job bro, many thanx to your tut

  89. Jhose Donzales Says:

    Good skills, just a lovely “Fist” typo at the top!

    FIST!

  90. Robin Says:

    Great work …

    I need to save the csv file after creation into a folder.. please give me sample to do that ..

    Appreciated

  91. bell418 Says:

    it works fine if I use scalc (openoffice) to test the output file :) ,
    but if I use my old-school-2003 excel to test the .csv output file,….no way!….
    ….commas are not recognized as separators :(

  92. bell418 Says:

    @Robin

    Robin :
    Great work …
    I need to save the csv file after creation into a folder.. please give me sample to do that ..
    Appreciated

    where do you want to save it, on the server or on a client computer?

  93. bell418 Says:

    @bell418
    …here is a solution if you want to put the file on your server in a folder:

    in exportcsv.inc.php take all the header-stuff away, also take away echo $out; and exit;
    …then add the folowing:

    $filename = ‘theway/tomyfolder/’.$filename; // of course you change theway/tomyfolder/
    if (!$handle = fopen($filename, ‘w’)) {
    echo “Impossible to open file : $filename”;
    }
    if (fwrite($handle, $out) === FALSE) {
    echo “Impossible to write to file : $filename”;
    }
    fclose($handle);

    ….an empty page will show-up, but the csv file is on your server where you want it to be
    this is only a sample!

  94. Matt Diecast Says:

    I’m trying to implement this function to run from a page within a WordPress website – basically a user who is viewing the DB table on the page has the option to click an export button to export the data to a CSV.

    The function is getting the data from the DB table fine, but is displaying it on the page rather than exporting to a CSV file. Does anyone know what is causing this, and how I can fix it?

    Thanks,

    Matt

  95. Travis2470 Says:

    I am a noob at this, should the two parts on top be in a file called exportcsv.inc.php? is is it two file and if so what do i call the first one?

  96. nobin Says:

    this code is excellent,
    it really works

    i want to add a feature more
    when i click in checkbox and select i data in the , i need just to export the seleted data
    how to

    means whichever data selected by checking in checkbox only that particular datas should be exported to excel or csv

  97. Nikki Cade Says:

    Hi

    Works a treat but I am missing the 0 off the front of the Telephone number column.

    Any ideas?

  98. binny Says:

    Gr8 script…thanks so much for saving our time……I can get the .csv file when the query is “select * from table” but my problem is that I want to get an array from the previous page and get the .csv file according to that query; my query would be:
    “select * FROM `portal` WHERE groups IN ($list)”. $ list is my array of values coming from previous page from a selectbox.
    Any help would be greatly appreciated.

  99. Bahb Says:

    @Ash Glover
    Had to do the same thing, here is what works.

    in, exportcsv.inc.php edit this,

    <?php
    function exportMysqlToCsv($table)
    {
    $today = date("F_j,_Y,_g:ia");
    $filename = "Info_Request__".($today).".csv";

  100. Shamsh Says:

    Nice work but what about multiple line inside one cell? I tried but not worked! Any suggestion?

  101. Jarad Says:

    This was so awesome. You my friend know how to do tutorials well. A straight-out-of-the-box solution for the coding-challenged.

  102. Nic Says:

    Hi for some reason IE does not want to download the file. I have tried in FF and Chrome and both worked.
    IE just pops up an error :
    “Unable to download statsDisplay.php form testarea.mydomain.com

    Unable to open this internet site.”

    Is there a specific option to choose from the headers?
    // header(“Content-type: text/x-csv”);
    //header(“Content-type: text/csv”);
    //header(“Content-type: application/csv”);
    i have added an if statement to check if i’m using IE and then to have another header uncommented.

    Content-type: text/csv works for FF and Chrome but none of the others work for IE.

    Any Ideas?

    Thanks for the script so far.

  103. asd Says:

    wow, thx!
    works fine for me.

  104. Alex Angelico Says:

    Why not using fputcsv PHP function? is this method safer?

  105. John Says:

    Hello,
    I used the function (with some changes) all was working as it should on a windows xp system, however not on a windows 7.

    function exportMysqlToCsv($filename = ‘Upload.csv’)

    {

    $csv_terminated = “\n”;

    $csv_separator = “,”;

    $csv_enclosed = ‘”‘;

    $csv_escaped = “\\”;

    $fields_cnt = 5;

    $schema_insert = ”;

    for ($i = 0; $i < $fields_cnt; $i++)

    {

    if($i=="0"){$temp="column 1";}

    if($i=="1"){$temp="column 2";}

    if($i=="2"){$temp="column 3";}

    if($i=="3"){$temp="column 4";}

    if($i=="4"){$temp="column 5";}

    $l = $csv_enclosed . $temp . $csv_enclosed;

    $schema_insert .= $l;

    $schema_insert .= $csv_separator;

    } // end for

    $out = trim(substr($schema_insert, 0, -1));

    $out .= $csv_terminated;

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    header("Content-Length: " . strlen($out));

    // Output to browser with appropriate mime type, you choose ;)

    header("Content-type: text/x-csv");

    //header("Content-type: text/csv");

    //header("Content-type: application/csv");

    header("Content-Disposition: attachment; filename=$filename");

    echo $out;

    exit;

    }
    Does somebody knows how to solve this problem ???
    Thanks in advance, John

  106. John Says:

    @John
    I, John, solved the problem it was a language isue, I changed Control Panel>Regional and
    Language options to English.

  107. irfan121us Says:

    Hi
    Im using ur code but im getting dis error msgs.

    Warning: mysql_num_fields(): supplied argument is not a valid MySQL result resource in /home/omangolf/public_html/admin/DownloadDetails.php on line 67

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/omangolf/public_html/admin/DownloadDetails.php on line 84

    Warning: Cannot modify header information – headers already sent by (output started at /home/omangolf/public_html/admin/DownloadDetails.php:11) in /home/omangolf/public_html/admin/DownloadDetails.php on line 115

    Warning: Cannot modify header information – headers already sent by (output started at /home/omangolf/public_html/admin/DownloadDetails.php:11) in /home/omangolf/public_html/admin/DownloadDetails.php on line 116

    Warning: Cannot modify header information – headers already sent by (output started at /home/omangolf/public_html/admin/DownloadDetails.php:11) in /home/omangolf/public_html/admin/DownloadDetails.php on line 118

    Warning: Cannot modify header information – headers already sent by (output started at /home/omangolf/public_html/admin/DownloadDetails.php:11) in /home/omangolf/public_html/admin/DownloadDetails.php on line 121

  108. lala Says:

    @John
    install office;)

  109. Shaun Santa Cruz Says:

    Thanks, this was exactly what I was looking for.

  110. johny Says:

    Thank’s man it’s work

  111. Pearl Says:

    Worked Perfectly! And it was just what I needed. Thank you so much for sharing- I just “bought” you a beer- wish I could afford more, I’m hoping that with enough “beers” you can pay for your time :)

  112. Michelle-lee Says:

    This is a great post it really help me finish up my final year project at school. I also learnt PHP amd Mysql at Tutorial arena

  113. sundarjaykumar Says:

    This code is working perfectly with little changes which are mandatory. Itz cool try………

  114. rr Says:

    Is there a way to make one html button calling this php function export 2 csv files from 2 separate tables with one click? Or do they have to be separate button.

  115. sets Says:

    Hi. Excellent script and has helped out more than I could ever say. Thanks.

    One thing I’m trying to do is relating to JT’s post on October 31st, 2009 at 3:22 where I’d like to change each column heading to begin with v_
    so something like product_id column heading would save as v_product_id and product_ model column heading would output v_product_model column heading and so on.

    I’ve tried JT’s example but it errors for me.

    Please could someone help me to get v_ at the start of each column heading?

    Thank you.

  116. cebu website design and development Says:

    thanks for this!!!

  117. Donovan Rittenbach Says:

    Thanks! That was quick and painless. I like that.

  118. PHP Coder Says:

    Excellent. I changed all the database connection and queries to fit my own database class. Everything works superb. Final output was perfect. Thank you for the code.

  119. Janne Särkelä Says:

    Thanks!

    I used your code as a part of complete example package about manipulating MySql database with PHP: http://www.sanaracreations.fi/web/an-example-of-manipulating-mysql-database-with-php-and-downloading-it-as-csv

  120. Shamim Says:

    Thanks! its great;

    If want to search my list and export only search result then what can i do…

  121. Bashar Says:

    Thank you very much, you just made my day

  122. BeverlyJ Says:

    Same basic question as Shamim: Works great to dump all records in table, but how can I substitute a query result for the $table var? Thank you for your great contribution in this site!

  123. Bruno Says:

    Congrats.

    Your code works perfect to me…. thx a lot

  124. Manish Says:

    Great Work. Worked for me too.

  125. maven Says:

    great article indeed. used and got it working in the first shot. excellent work. thank you.

    and God bless.

  126. Paulraj Says:

    Good Work… Thanks !

  127. Merle Durisseau Says:

    You actually make it appear really easy along with your presentation however I find this matter to be actually one thing that I think I might never understand. It sort of feels too complex and very broad for me. I am looking forward to your next put up, I’ll attempt to get the grasp of it!

  128. Gertude Hirtz Says:

    you’re truly a just right webmaster. The site loading pace is incredible. It kind of feels that you are doing any unique trick. In addition, The contents are masterpiece. you have performed a magnificent task in this matter!

  129. Mike Says:

    When i use this, the first row is empty and then the column names show up on row 2 and the results below that… what should i do to get rid of the empty first row (sorry if i missed this somewhere).

  130. amit Says:

    thanks dear…. useful script 4 me..

  131. Kendal Muro Says:

    Thank you for your post.Really thank you! Fantastic.

Leave a Reply