-
Mysql To Excel Via Php
Greetings all,
I have a php script which produces an excel file from the requested table. It works fine except for getting the field names as header in the excel file. Can't get it to work and am out of ideas. Any help will be appreciated.
The code is below:
<?php
//YOUR DATABASE HOST = (ex. localhost)
//USERNAME = username used to connect to host
//PASSWORD = password used to connect to host
//DB_NAME = your database name
//TABLE_NAME = table in the database used for extraction
$select = "SELECT * FROM specialized_tbl";
$export = mysql_query($select);
$count = mysql_num_fields($export);
//************
//Extract field names and write them to the $header variable
//***********/
for ($i = 0; $i < $count; $i++) {
$header .= mysql_field_name($export, $i)."\t";
}
//***********
//Extract all data, format it, and assign to the $data variable
///**********/
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("r", "", $data);
//************
//Set the default message for zero records
if ($data == "") {
$data = "n(0) Records Found!n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=specialized.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$headern$data";
?>
-
This is the one I always use:
PHP Code:
<?
header ('Content-type: application/x-msexcel');
// Connection Script here
$sql = "SELECT * FROM TABLENAMEHERE";
$excel = mysql_query($sql);
$columns = mysql_num_fields($excel);
$i = 0;
echo "<table border=\"1\">";
while ($row = mysql_fetch_array($excel))
{
if ($i == 0)
{
echo "<tr>";
for ($j=0; $j<$columns; $j++)
echo "<td>". mysql_field_name($excel, $j) ."</td>";
echo "</tr>";
$i++;
}
echo "<tr>";
for ($j=0; $j<$columns; $j++)
echo "<td>". $row[$j] ."</td>";
echo "</tr>";
}
echo "</table>";
?>
-
Thanks
Thanks,
I shall give it a go!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|