jotamon
jotamon

Reputation: 1613

save csv to server from mysql via php

I can create a csv from mysql that is then saved on the user's computer via the code below.

        //Connecting to my database
        mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
        mysql_select_db($dbname);               


        // output headers so that the file is downloaded rather than displayed
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=pikaObs_'.date("Ymd").'.csv');            


        // create a file pointer connected to the output stream
        $output = fopen('php://output', 'w');

        // output the column headings
        fputcsv($output, array('fid','firstName','lastName','email','phone','date','time','pikasSeen','haystacksSeen','pikasHeard','pikasDoing','habitatType','lattitude','longitude'));

        // fetch the data
        mysql_connect($hostname, $username, $password);
        mysql_select_db($dbname);
        $rows = mysql_query('SELECT * FROM pikaObs');

        // loop over the rows, outputting them
        while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

What I want to do now is write a php script that will save this csv to the server rather than prompting and storing on the user's machine.

Can I modify the above code to save a new file stamped with date time to a folder on the server?

Upvotes: 1

Views: 2265

Answers (1)

hek2mgl
hek2mgl

Reputation: 158250

Simple answer: Let $output point to a file:

// create a file pointer connected to a file
$output = fopen('/path/to/yourfile', 'w+');

and remove the calls to header()

Upvotes: 2

Related Questions