How to export returned datatable to excel with PHP
Sounds simple, but I do not know where to start.
My site has a series of selections the user picks from. From that
selection, a query is built, and data is pulled from the database. It is
then returned in a table format.
At this point, the data is displayed and the user can click a button to
export the records into an Excel sheet.
Here is the query:
<?php
function displayrecords(){
$place = $_GET['place'];
$time = $_GET['time'];
$name = $_GET['name'];
$sql_json = "";
$where = "";
if($place != ""){
$where = " `place` = '".mysql_real_escape_string($place)."'";
}
if($time != ""){
if( $where != "" ) $where .= " AND ";
$where .= " `time` = '".mysql_real_escape_string($time)."'";
}
If($name != ""){
if( $where != "" ) $where .= " AND ";
$where .= " `name` = '".mysql_real_escape_string($name)."'";
}
if ($where != "") $sql_json = "SELECT * FROM `database`" . " WHERE " .
$where . ";";
$QueryResult = @mysql_query($sql_json) or die ('<div>Use filters to
search</div>');
$resnum = mysql_num_rows($QueryResult);
if ($resnum == 0){
echo "<div>Your search returned no results</div";
}
else {
echo "<table>\n";
echo "<tr><th>Place</th>" . "<th>Time</th>" . "<th>Name</th></tr>\n";
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE){
echo "<tr><td>{$Row[place]}</td>";
echo "<td>{$Row[time]}</td>";
echo "<td>{$Row[name]}</td></tr>";
};
echo "</table>\n";
}
}
?>
I can call the function in html at this point:
<?php displayrecords(); ?>
Then here is my button used to export:
<input class="btn btn-success btn-small" type="submit" name="get_report"
value="Get Report" />
And this is where I'm stuck. I know I might have to use javascript or
something. Please provide me some insight. No need to down my code. I'm
using regular mysql, not mysqli or pdo.
Please tell me what I need to do next to make the button work so it
exports to an Excel sheet. I'd appreciate your help.
Thank you.
No comments:
Post a Comment