Advertisement
Guest User

Untitled

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