Take the 2-minute tour ×

How do I put a download button on a site to get a CSV of a table Query?

Currently I am using "SELECT * INTO OUTFILE" to make the CSV file on the sever HD and is fine except...

I want to create the CSV like I am now, but I want the "OUTFILE" to be saved on the clients computer when they click Download.

// Create new file name for file to be created 
$csvfilename = "/dropbox/consolodated-" . date("Y-M-d_H-i-s") . ".csv";

mysql_query ("SELECT * INTO OUTFILE '$csvfilename' FIELDS TERMINATED BY ',' FROM people ");

<H2>Done - File created - Now download it from FTP site.</H2>

Thanks for the Help - Merry Christmas

share|improve this question
You probably have a typo in $csv-filename. –  Alix Axel Dec 24 '09 at 7:27
Thanks Alix, Replaced $csv-filename with $csvfilename. –  Ken Butcher Dec 28 '09 at 4:13

4 Answers 4

The solution to this can be that:

  • First you save the csv file on to server.
  • then get it's path
  • and finally create an anchor tag with its path for download eg:


 <a href="pathtoyourcsvfile.csv">Download</a>
share|improve this answer
+1 for the simple approach, the CSV file has to be stored on a public accessible location though. –  Alix Axel Dec 24 '09 at 7:26

Add a POST form at the end which includes a hidden field containing the filename (but NOT the path!) of the file to download. Then have the page it POSTs to read the variable and offer the file for download. Don't forget to enable output buffering and to occasionally flush so that the form is not visible until the query has completed.

share|improve this answer

Simple, here is a sample snippet:



And here is the download function:

function Download($path, $speed = null)
    if (is_file($path) === true)

    	while (ob_get_level() > 0)

    	$size = sprintf('%u', filesize($path));
    	$speed = (is_null($speed) === true) ? $size : intval($speed) * 1024;

    	header('Expires: 0');
    	header('Pragma: public');

    	for ($i = 0; $i <= $size; $i = $i + $speed)
    		echo file_get_contents($path, false, null, $i, $speed);



    return false;

Merry Xmas to you too! =)

share|improve this answer
Thanks, I have this quirky desire to fully understand what I copy and paste, so thanks to your help I am now going through the "Output Buffering Control" and "header" sections of PHP.net and it looks like this is what I am looking for. The more you know - the more you know you don't know. –  Ken Butcher Dec 28 '09 at 4:24

Your Answer


