Export MYSQL data into Excel/CSV via php
- Date: Feb 26, 2010
- Author: Rakshit Patel
- Comments: 59
- Tags: Export data into CSV using PHP, Export from MYSQL to Excel, Export MYSQL data into CSV/Excel file, Export to Excel/CSV with PHP/MYSQL, From MYSQL to CSV, From MYSQL to Excel, Important PHP Functions, php script, PHP/MYSQL export to CSV/Excel(xls)
- Categories: Helpful Tips and Tricks, MYSQL, PHP Programming
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 ?
$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";
$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-Disposition: attachment; filename=reports.xls");
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.