View Full Version : Retrieve data from a mysql database to excel

09-04-2009, 12:27 PM
I have this code that retrieves data from a mysql database and exports it into excel.

Now is my question how to get the column names in excel (above the records).


$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "username"; //your MySQL User Name
$DB_Password = "password"; //your MySQL Password
$DB_DBName = "database";

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());

$Db = @mysql_select_db($DB_DBName, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());

$query = "SELECT * FROM nbs_vmb_contacts where nbs_vmb_group_id = '2' ";
$result = mysql_query($query) or die('Error, query failed');

$tsv = array();
$html = array();
while($row = mysql_fetch_array($result, MYSQL_NUM))
$tsv[] = implode("\t", $row);
$html[] = "<tr><td>" .implode("</td><td>", $row) . "</td></tr>";

$tsv = implode("\r\n", $tsv);
$html = "<table>" . implode("\r\n", $html) . "</table>";

$fileName = 'mysql-to-excel.xls';
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$fileName");

echo $tsv;
//echo $html;

09-04-2009, 04:14 PM
Just stick em in there prior to writing out the data from the database.