I have a MSSQL database table I’m accessing on a PHP page. I’m displaying certain rows on the page using a SELECT ALL WHERE query. Now I need a button to export the SELECT ALL WHERE query to a .csv file. I need a little help getting started with this.
I have a function to create the page that could create the page to export:
public function SelectAllWhereFetch( $table, $where, $extra = "", $columns = "*" ) {
$tsql = "SELECT $columns FROM " . $table . " WHERE " . $where . $extra;
$stmt = $this->ExecuteDontFreeQuery( $tsql );
$result = mssql_query($query);
// Checking for and creating table names
$i = 0;
echo '<html><body><table><tr>';
while ($i < mssql_num_fields($result))
{
$meta = mssql_fetch_field($result, $i);
echo '<td>' . $meta->name . '</td>';
$i = $i + 1;
}
echo '</tr>';
// Returning all rows in table
while ( ($row = mssql_fetch_row($result)))
{
$count = count($row);
$y = 0;
echo '<tr>';
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
}
mssql_free_result($result);
echo '</table></body></html>';
}
Here’s the “if” statement for the button action:
if( $_REQUEST['exporting']) {
$vastreamline = $dataConnection->SelectAllWhereFetch("applicants",
"loan_purpose='VA Streamline' AND statusdate >= '1/1/2011'",
"ORDER BY statusdate DESC" );
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=streamline.csv");
echo $vastreamline;
}
Here’s the button action:
<div class="span3">
<input type="hidden" name="exporting" value="true">
<input type="submit" class="btn primary" value="Export CSV">
</div>
I seem to be making a connection to the MSSQL database because I can display information. I just can’t figure out the syntax to get the button to export a csv file.
Since your button is not inside of a form, try:
Also change your PHP export page to: