HTML download button for SQL query?

Soldato
Joined
28 Sep 2008
Posts
14,184
Location
Britain
Hi guys,

I want a button which, when users click, it downloads a csv file which returns all the results from a MySQL database.

Using PHP, here's what I had

PHP:
<p>Export all contacts from within the database to a CSV file</p>

<form><input type="button" value="Download Now" onClick="<?php
SELECT * INTO OUTFILE 'c:/mydata.csv' FROM contacts;

?>"
</form>
<br />

But it's not working :(

Any ideas?
 
Ok, I should have added (but I didn't put it in the code). All the relevant connection data is at the top of the sheet linked to via an /includes/config.php file. There's already a connection to the database.

I thought that phpmyadmin used to show you the queries it ran when outputting to a file. I assume this would be sufficient, but I can't seem to find those queries anymore :(
 
All the results already display, nicely, on the webpage. However, I need a "one button" click solution so that they can "export" the entire table to their machines for use within Excel :)

I looked at that solution, but it only seems to return the results
 
Cool, I've got it working now:

csv.php
PHP:
<?php
session_start();
require_once('includes/config.php');

if(!$_SESSION['user']['username']) {
       //not logged in. redirect to login page
       header("Location: login.php");
       exit;
}
$result = mysql_query('SELECT * FROM `contacts`');  
if (!$result) die('Couldn\'t fetch records');  
$num_fields = mysql_num_fields($result); 
$headers = array();  
for ($i = 0; $i < $num_fields; $i++)  
{            
$headers[] = mysql_field_name($result , $i);
}  
$fp = fopen('php://output', 'w');
if ($fp && $result)  
{            
 header('Content-Type: text/csv');       
 header('Content-Disposition: attachment; filename="export.csv"');
 header('Pragma: no-cache');
 header('Expires: 0'); 
 fputcsv($fp, $headers); 
while ($row = mysql_fetch_row($result))
{ 
fputcsv($fp, array_values($row)); 
} die;
} 
 
?>

and the HTML

Code:
<form action="csv.php">
<input type="submit" value="Download Now">
</form>

:)
 
Last edited:
Back
Top Bottom