Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active October 30, 2016 18:17
Show Gist options
  • Save surferxo3/9ff96d81a066ef90e4f90145bee18996 to your computer and use it in GitHub Desktop.
Save surferxo3/9ff96d81a066ef90e4f90145bee18996 to your computer and use it in GitHub Desktop.
Script to export data from MySQL in Excel.
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
function exportToExcel($host, $user, $pass, $db, $query) {
$conn = mysql_connect($host, $user, $pass);
$db = mysql_select_db($db,$conn);
$rec = mysql_query($query) 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=dump.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo "$header\n$data";
}
@surferxo3
Copy link
Author

If you want to export data from any other db just replace the database connecting function and the rest will work as same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment