Guest User

Untitled

a guest
Dec 6th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. <?php
  2. /* vars for export */
  3. // database record to be exported
  4. $db_record = 'foo';
  5. // optional where query
  6. $where = '';
  7. // filename for export
  8. $csv_filename = 'dbExport' .$db_record. '_' .date('m-d-Y').'.csv';
  9. // database variables
  10. $hostname = "localhost";
  11. $user = "XXXXX";
  12. $password = "XXXXX";
  13. $database = "XXXXX";
  14. $port = 3306;
  15.  
  16. $conn = mysqli_connect($hostname, $user, $password, $database, $port);
  17. if (mysqli_connect_errno()) {
  18. die("Failed to connect to MySQL: " . mysqli_connect_error());
  19. }
  20. // create empty variable to be filled with export data
  21. $csv_export = "\xEF\xBB\xBF";
  22.  
  23. // query to get data from database
  24. $query = mysqli_query($conn, "SELECT * FROM ".$db_record." ".$where);
  25. $field = mysqli_field_count($conn);
  26.  
  27. // create line with field names
  28. for($i = 0; $i < $field; $i++) {
  29. $csv_export.= '"' . mysqli_fetch_field_direct($query, $i)->name . '"';
  30. if($i < ($field-1)){
  31. $csv_export.=',';
  32. }
  33. }
  34.  
  35. // newline (seems to work both on Linux & Windows servers)
  36.  
  37. $csv_export.= "\r\n";
  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.= '"'.addslashes($row[mysqli_fetch_field_direct($query, $i)->name]).'"';
  44. if($i < ($field-1)){
  45. $csv_export.=',';
  46. }
  47. }
  48. $csv_export.= "\r\n";
  49. }
  50. // Export the data to a location on the server
  51.  
  52. $dir = '/directory/you/want/to/write/to/goes/here' . $csv_filename;
  53. $handle = fopen($dir, 'w+');
  54. fwrite($handle, $csv_export);
  55. fclose($handle);
  56. ?>
Add Comment
Please, Sign In to add comment