Export MYSQL data into Excel/CSV via php
Hello Friends,
Today i came across a functionality where i need to Export the MYSQL data into CSV/Excel file via PHP function/script. There are such requirement where client needs to Export the MYSQL data (Order data,Member data,Newsletter emails etc) into Excel sheet or CSV file for future reference or need to send to other team for future work. You can give a button or link from where client can click on it and get a Excel or CSV file with all data from MYSQL database tables using(through) PHP.
Here i am sharing a function using which you can easily export the MYSQL data into Excel/CSV with a single click on button or link. If you are looking to export the filtered data than you can pass parameters into function and make a sql query accordingly. Do you know how to Import CSV/Excel data into MYSQL ?
<?php
function export_excel_csv()
{
$conn = mysql_connect("localhost","root","");
$db = mysql_select_db("database",$conn);
$sql = "SELECT * FROM table";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\\t";
}
while($row = mysql_fetch_row($rec))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
{
$data = "\\n No Record Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
}
?>
What you need to do is…
1) Copy above function and paste it into your file.
2) Change MYSQL connection settings in mysql_connect("localhost","root","").
3) Change database name in mysql_select_db("database",$conn)
4) Change table name in $sql = "SELECT * FROM table".
5) Thats it.
Let me know your thoughts for the same. If you face any problem in this than let me know via comment or contact us form.
To know more about programming,JavaScript issues,jQuery,Expression Engine,MYSQL database and Open-source, enter your email address below. We will send you free tutorials.






I am
about 2 years ago
This is an informative post…Useful foe web mining too
about 2 years ago
This is an informative post…Useful foe web mining too
about 2 years ago
hi
really it was very useful and easy trick to export to excel, however i am a new person to this build a site and using PHP,
as per your instrcution, i did change db connection, table etc, but i do not know how to link with that " export to excel" word to this file to export to excel, please advise me
it will be thankful your and your site..
thanks
ilyas
about 2 years ago
hi
really it was very useful and easy trick to export to excel, however i am a new person to this build a site and using PHP,
as per your instrcution, i did change db connection, table etc, but i do not know how to link with that " export to excel" word to this file to export to excel, please advise me
it will be thankful your and your site..
thanks
ilyas
about 2 years ago
Hi ilyas,
how to link with that " export to excel" word to this file to export to excel — You can submit the form on onclick event OR redirect to any page with a link, and than make a call to the above function. Once you will call this function, it will popup for Open/Save the excel file.
Let me know if any confusion.
Thanks,
Rakshit Patel.
about 2 years ago
Hi ilyas,
how to link with that " export to excel" word to this file to export to excel – You can submit the form on onclick event OR redirect to any page with a link, and than make a call to the above function. Once you will call this function, it will popup for Open/Save the excel file.
Let me know if any confusion.
Thanks,
Rakshit Patel.
about 2 years ago
Hi,
Good script.
but didnt get the meaning of "t" and "n".
about 2 years ago
Hi,
Good script.
but didnt get the meaning of "t" and "n".
about 2 years ago
@chirag .. It is t and n. I have corrected it. thanks.
about 2 years ago
@chirag .. It is \t and \n. I have corrected it. thanks.
about 1 year ago
this is an interesting code
about 1 year ago
the code does produce a .xls file but non of my information is in cells, they are just all put together in one cell with quotes separating them.
ex.
“4″”Bob”"”"seary”"”"bobn@hotmail.com”"”"Super cool”"”"worker”"”"555555″”idoscope”"”"No”"”
about 1 year ago
thank u so much for your helpful script…. its working fine..
about 1 year ago
When I try to implement this code with a couple of date parameters passed into the function, I end up with the csv string just printing in my browser window, and I never get the save dialog.
about 11 months ago
The download option is not popping up for me. Any suggestions? Ive tested in IE, FF, Chrome, and Safari.
about 9 months ago
Very useful and exact one. Thanks
about 9 months ago
Export MYSQL data into Excel/CSV via php
hi
really it was very useful and easy trick to export to excel, however i am a new person to this build a site and using PHP,
as per your instrcution, i did change db connection, table etc, but i do not know how to link with that ” export to excel” word to this file to export to excel, please advise me
it will be thankful your and your site..
thanks
about 8 months ago
I think the mySQL => CSV is common problem which is part of each PHP forum. I have try to solve this issue in a common way and implement an free export lib for PHP which is very similar to the Google AppInventor philosophie. DragDrop and hide the coding stuff.
Use the lib and create your Export via Click&Point.
worth a look
Greetings
Andreas
about 8 months ago
how can i run this program.
about 7 months ago
Sorry but it is not working for me. If you have corrected the \\t and \\n, where can we get the corrected version
about 7 months ago
the above code has a problem it is showing /t and /n in excel file and all data comes in single cell so i corrected the code and now its working fine look at below code you must take this code its working.
<?php
include 'connection.php';
function export_excel_csv()
{
$sql = "SELECT * FROM sanghar_centers";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
for($i = 0; $i
about 4 months ago
Hi,
I’am having 2 problems with this code.
First the i get no popup but is shows data in the page.
And 2nd the data is ok but when i put it in a .xls it is all in the same cell.
Howto fix this ?
Thanks
Koen
about 3 months ago
How are you expected to use this.. ?
about 3 months ago
Hi,
The above give code has some error. I have solve that error For the working copy of Export to Excel or CSV go to below given Address
http://source-coding.blogspot.com/2012/01/export-mysql-data-into-excelcsv-via-php.html
about 3 months ago
It didn’t work for me
about 3 months ago
no pop up, displays the page but no data. i really need your help. we are doing our thesis and one of our feature is to export a csv file comming from the database mysql. if you can help me.
THank you so much!:)
about 2 months ago
hey it is being download but in xml file there is notice shown
Notice: Undefined variable: header in D:\xampp-win32-1.7.7-VC9\xampp\htdocs\back.php on line 15
Notice: Undefined variable: data in D:\xampp-win32-1.7.7-VC9\xampp\htdocs\back.php on line 34
about 1 month ago
Nice script, it works very well but i Had to add a call to ob_clean() function before to call header in order to clean any garbage, The otherproblem I have is that all exports have /body and /html tags at the end of the file
about 1 week ago
this code was really helped me to learn about extracting…but ther is a problem in code. it will produce only the last line of the table….i dont know how to change the coding to start from the fst row. pls help….