Export MySQL query to Excel
5
This is a cool function that lets you save MySQL query data to an Excel spreadsheet. This is good for taking a backup or if you want to change a lot of information fast, then re-upload it.
I will use the config.php and class.mysql.php files from MySQL DB Class with Extras, so please look at those also.
I will use the config.php and class.mysql.php files from MySQL DB Class with Extras, so please look at those also.
<?php
require_once "config.php";
require_once "class.mysql.php";
$db = new mysql();
function downloadXL($sql, $filename){
global $db;
$export = $db->query($sql);
$fields = $db->numFields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= $db->fieldName($export, $i) . "\t";
}
while($row = $db->fetchRow($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$value = stripslashes($value);
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r","",$data);
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
}
$sql = "SELECT first_name, last_name, username, password FROM users";
$filename = "Users_Information";
downloadXL($sql, $filename);
?>






There are currently no comments for this snippet.