0

I have recently made a website and have a members table in my sql. I have an admin page that has the ability to download that with column names; however I used to use INTO OUTFILE but that is not allowed on my host. I came up with this code to download the file:

if(file_exists('downloads/members_'.date("m-d-Y").'.csv') == true) {
    header("Location: /downloads/members_".date("m-d-Y").".csv");
}   

$output = fopen('downloads/members_'.date("m-d-Y").'.csv', 'w+');

fputcsv($output, array('memberID','username', 'password', 'email', 'active', 'resetToken', 'resetComplete', 'support', 'supportToken' ));

$rows = mysql_query("SELECT * FROM members;");
while ($row = mysql_fetch_assoc($rows)) fputcsv($output,$row);
header("Location: /downloads/members_".date("m-d-Y").".csv");
exit;

This just outputs the column names and I have never used fputcsv before and am a tad confused on what I am doing wrong. I get the file to download but not with the table in it.

[EDIT] I just tried it with a valid sql query and it does not work. updated code above. Also There is stuff in the members table.

3
  • Are you sure result set from query is not empty? Commented Apr 2, 2016 at 16:55
  • This is not a valid sql statement: SELECT * FROM 'members';. Commented Apr 2, 2016 at 16:57
  • Have you tested my answer? If it does not work, tell me your errors. Commented Apr 2, 2016 at 18:55

1 Answer 1

1

Try this:

if (isset($_POST['download'])) {
    $result = mysql_query("SELECT * FROM members", $connection);
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=yourcsv.csv');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    $csvoutput = fopen('php://output', 'w');
    $row = getRow($result);
    $headers = array_keys($row);//columns from db e.g, memberID','username',...
    fputcsv($csvoutput, $headers);
    fputcsv($csvoutput, $row);
    while ($row = getRow($result)) {
        fputcsv($csvoutput, $row);
    }
    fclose($csvoutput);
    exit;
   }

Here is your getRow() function:

 function getRow($res){
     return mysql_fetch_assoc($res);
   }

And in your html:

<input type="submit" name="download" value="Download CSV">

Here is realtime demo with sqllite3 database. Uncomment the create database and insert statement in order to see the working demo. I have tested and it is working fine. I hope this will help you.

Sign up to request clarification or add additional context in comments.

2 Comments

It outputs an blank/invalid csv
I have updated my answer with working demo. If it helps, please click the tick icon above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.