Reputation: 78
I'm new to PHP and I'm trying to do a small experiment to learn.
I want to create a line of words, that when clicked, will download a csv file from a table I have in my database.
So far, this is what I've come up with (which isn't even near what I want to do. But I was able to make it turn into a hyperlink).
echo "<a href=http://www.google.com>Click here to visit site</a>";
Assuming I already have a connection to my database, how would I go about connecting "Click here to visit site" to download a csv file, from say, table1 of my database ABC?
I think there will have to be some loop that reads the rows in table1 and writes it into the csv file, right?
Upvotes: 0
Views: 88
Reputation: 5662
Create a file separate file having the following code and create a hyperlink in your current file like:
echo "<a href='http://<your domain name>/test.php'>Click here to visit site</a>";
<?php
//test.php
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
$rows = mysqli_query($conn, 'SELECT name, email FROM users limit 10');
// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
?>
Upvotes: 1