Advertisement
Guest User

Untitled

a guest
Jun 20th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. <?php
  2.  
  3. /* vars for export */
  4. // database record to be exported
  5. $db_record = 'XXX_TABLE_NAME_XXX';
  6. // optional where query
  7. $where = 'WHERE 1 ORDER BY 1';
  8. // filename for export
  9. $csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';
  10. // database variables
  11. $hostname = "XXX_HOSTNAME_XXX";
  12. $user = "XXX_USER_XXX";
  13. $password = "XXX_PASS_XXX";
  14. $database = "XXX_DATABASE_XXX";
  15. $port = 3306;
  16.  
  17. $conn = mysqli_connect($hostname, $user, $password, $database, $port);
  18. if (mysqli_connect_errno()) {
  19. die("Failed to connect to MySQL: " . mysqli_connect_error());
  20. }
  21.  
  22. // create empty variable to be filled with export data
  23. $csv_export = '';
  24.  
  25. // query to get data from database
  26. $query = mysqli_query($conn, "SELECT * FROM ".$db_record." ".$where);
  27. $field = mysqli_field_count($conn);
  28.  
  29. // create line with field names
  30. for($i = 0; $i < $field; $i++) {
  31. $csv_export.= mysqli_fetch_field_direct($query, $i)->name.';';
  32. }
  33.  
  34. // newline (seems to work both on Linux & Windows servers)
  35. $csv_export.= '
  36. ';
  37.  
  38. // loop through database query and fill export variable
  39. while($row = mysqli_fetch_array($query)) {
  40. // create line with field values
  41. for($i = 0; $i < $field; $i++) {
  42. $csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";';
  43. }
  44. $csv_export.= '
  45. ';
  46. }
  47.  
  48. // Export the data and prompt a csv file for download
  49. header("Content-type: text/x-csv");
  50. header("Content-Disposition: attachment; filename=".$csv_filename."");
  51. echo($csv_export);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement