Export MySQL Data as CSV


/ Published in: PHP
Save to your folder(s)

# Export MySQL Data as CSV

This code takes a `mysql_query()` resource and outputs its rows into CSV spreadsheet format. Edit the `header('Content-Disposition...` declaration to tell the user's browser to either display the data as plain text or download it as an `attachment`.

__Note:__ This doesn't include the code to connect to the database in the first place. Don't forget that, otherwise this code is pretty useless.


Copy this code and paste it in your HTML
  1. $result = mysql_query("SELECT * FROM table ORDER BY column DESC");
  2.  
  3. // I hard-code the column names so I can capitalize, add spaces, etc.
  4. $fields = '"User ID","Name","Email","Registration Date"'."\n";
  5.  
  6. // Iterate through the rows of data
  7. while ($row = mysql_fetch_assoc($result))
  8. {
  9. $fields .= '"'.$row['id'].'","'.$row['name'].'","'.$row['email'].'","'.$row['registration_date'].'"'."\n";
  10. }
  11.  
  12. // Set our headers
  13. header('Content-type: text/csv');
  14. // To display data in-browser, change the header below to:
  15. // header("Content-Disposition: inline");
  16. header("Content-Disposition: attachment; filename=event_registrations.csv");
  17.  
  18. // Output our data
  19. echo $fields;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.