I have a form that writes data to a MySQL database. I want the user to be able to download their data in CSV format after final submission.
My code is currently dumping the contents of the database into the browser, i.e. it is being written to the page, rather than to a csv file. I would like to send them to a link and be given the option to download a file.
Here is my current code:
$dbo = new PDO('mysql:host=localhost;dbname=db1', $username, $password);
$sql = "SELECT * FROM table1";
$qry = $dbo->prepare($sql);
// Execute the statement
$qry->execute();
var_dump($qry->fetch(PDO::FETCH_ASSOC));
$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
echo "Success";
// Export every row to a file
fputcsv($data, $row);
}
The current result is a page with a dump of all the data from the table. No file is being created in the location desired. Where am I going wrong?