Tuesday, September 28, 2010

Export Data From MySql DatabaseTable to Excel

$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "root"; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = "test"; //your MySQL Database Name
$DB_TBLName = "users"; //your MySQL Table Name
$ttype = $DB_TBLName;

$sql = "Select * from $DB_TBLName";

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)
or die("Couldn't connect to MySQL:
" . mysql_error() . "
" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect)
or die("Couldn't select database:
" . mysql_error(). "
" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect)
or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());


while($row = mysql_fetch_row($result,MYSQL_ASSOC))
{
$data[] = $row;

}
//print_r($data);exit;

function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}

// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) {
//display field/column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\n";
}
exit;