views:

71

answers:

4

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.

<?php
// 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

+1  A: 

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>
Sarfraz
+1 for the simple approach, the CSV file has to be stored on a public accessible location though.
Alix Axel
A: 

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.

Ignacio Vazquez-Abrams
A: 

Simple, here is a sample snippet:

$csv_filename = "/dropbox/consolodated-" . date("Y-M-d_H-i-s") . ".csv";

Download($csv_filename);

And here is the download function:

function Download($path, $speed = null)
{
    if (is_file($path) === true)
    {
     set_time_limit(0);

     while (ob_get_level() > 0)
     {
      ob_end_clean();
     }

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

     header('Expires: 0');
     header('Pragma: public');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Content-Type: application/octet-stream');
     header('Content-Length: ' . $size);
     header('Content-Disposition: attachment; filename="' . basename($path) . '"');
     header('Content-Transfer-Encoding: binary');

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

      flush();
      sleep(1);
     }

     exit();
    }

    return false;
}

Merry Xmas to you too! =)

Alix Axel
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