Advertisement
Guest User

Untitled

a guest
Jun 20th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 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; //Change the Port if you do not use the MySQL default port
  16.  
  17.  
  18. $conn = mysqli_connect($hostname, $user, $password, $database, $port);
  19.  
  20. if (mysqli_connect_errno()) {
  21. die("Failed to connect to MySQL: " . mysqli_connect_error());
  22. }
  23.  
  24. // create empty variable to be filled with export data
  25. $csv_export = '';
  26. // query to get data from database
  27. $query = mysqli_query($conn, "SELECT * FROM ".$db_record." ".$where);
  28.  
  29. $field = mysqli_field_count($conn);
  30. // create line with field names
  31. for($i = 0; $i < $field; $i++) {
  32.  
  33. $csv_export.= mysqli_fetch_field_direct($query, $i)->name.';';
  34. }
  35.  
  36. // newline (seems to work both on Linux & Windows servers)
  37. $csv_export.= '
  38. ';
  39. // loop through database query and fill export variable
  40. while($row = mysqli_fetch_array($query)) {
  41. // create line with field values
  42. for($i = 0; $i < $field; $i++) {
  43. $csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";';
  44. }
  45. $csv_export.= '
  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