I got a Query that in one scenario I execute the query and it displays the results in a table format with data and headers etc… The second scenario I want to creat is a direct download link that will execute the query and put the results into a .csv file for saving or opening in Excel. I have the code for the display already but I am wondering how to make it download for the user.
Here is a tidbit of code for the execute and display.
<?php
$month = $_POST['mydate'];
$monthfrm = date("Y-m-d", strtotime($month));
$monthhd = date("F", strtotime($month));
$monthto = date("Y-m-d", strtotime("$monthfrm . +1 month"));
$date = date("F j,Y");
if ($_POST['credsubmit']) {
print('<head>');
print('<link href="helper.css" media="screen" rel="stylesheet" type="text/css" />');
print('<link href="dropdown.css" media="screen" rel="stylesheet" type="text/css" />');
print('<link href="default.css" media="screen" rel="stylesheet" type="text/css" />');
// Connecting, selecting database
$dbconn = pg_connect("yeah we all know what goes here");
if (!$dbconn) {
die('Could not connect: ' . pg_last_error());
}// Performing SQL query
$query = "
SELECT cm.\"ID\",a.\"ID\" as \"DDI\",cm.\"Date\",c.\"Amount\",ct.\"Name\" as \"Name\",cm.\"Comments\" as \"Comments\"
FROM \"BIL_CreditMemo\" cm
LEFT JOIN \"BIL_Credit\" c ON (c.\"ID\" = cm.\"BIL_CreditID\")
LEFT JOIN \"ACT_Account\" a ON (c.\"ACT_AccountID\" = a.\"ID\")
LEFT JOIN \"BIL_val_CreditMemoReason\" ct ON (ct.\"ID\" = cm.\"BIL_val_CreditMemoReasonID\")
WHERE cm.\"Date\" >= '$monthfrm' AND cm.\"Date\" < '$monthto';
";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<h2 align=center style=margin-top:20>Credit Memo Report for: $monthhd</h2>";
echo "<table align=center width=60%>\n";
print('<tr class="trstyle"><td>ID</td><td>DDI</td><td>Date</td><td>Amount</td><td>Name</td><td>Comments</td></tr>');
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";// Free resultset
pg_free_result($result);// Closing connection
pg_close($dbconn);
}
?>
So that is what I got so far and want to make the results a direct download to a csv file? Any help is greatly appreciated.
You need to set a few HTTP headers, then you just echo out CSV data. For example,
Note that if you’re specifically targeting Excel, then there are libraries that will allow you to create .xls files; I quite like PHPExcel