Here's my PHP code to create a .CSV file based on some SQL data. It's working as intended, the only issue being that it simply creates a .CSV file on the server, and doesn't prompt the user to download it.
<?php
require_once "../assets/repository/mysql.php";
$query = "SELECT * FROM datashep_AMS.COMPLETE_APPLICATIONS";
$results = mysql_query($query);
$first = true;
$out = fopen('export.csv', 'w');
while($row = mysql_fetch_assoc($results)){
if($first){
$titles = array();
foreach($row as $key=>$val){
$titles[] = $key;
}
fputcsv($out, $titles);
$first = false;
}
fputcsv($out, $row);
}
fclose($out);
?>
So my question is, how do I make the user download the file immediately upon it being generated?
And, once they've downloaded it (or declined), how should I handle deleting the .CSV file from my server?
Try... csv download. <? php mysql_connect('hostname', 'username', 'password'); mysql_select_db('dbname'); $qry = mysql_query("SELECT * FROM tablename"); $data = ""; while($row = mysql_fetch_array($qry)) { $data . = $row['field1'].
Export data to a text file by saving itGo to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).
no need to store anything on the server (and thus no need to delete ...). Just write the results back to the browser and set the headers accordingly:
<?php
require_once "../assets/repository/mysql.php";
$query = "SELECT * FROM datashep_AMS.COMPLETE_APPLICATIONS";
$results = mysql_query($query);
$first = true;
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="export.csv"');
header('Cache-Control: max-age=0');
$out = fopen('php://output', 'w');
while($row = mysql_fetch_assoc($results)){
if($first){
$titles = array();
foreach($row as $key=>$val){
$titles[] = $key;
}
fputcsv($out, $titles);
$first = false;
}
fputcsv($out, $row);
}
fclose($out);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With