SHARE
TWEET

Untitled

a guest May 23rd, 2019 183 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /* vars for export */
  3. // database record to be exported
  4.  
  5. $db_record = '2pix';
  6. // optional where query
  7. // filename for export
  8. $csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';
  9. // database variables
  10. $hostname = "localhost";
  11. $user = "db-user";
  12. $password = "db-pass";
  13. $database = "db-name";
  14. $port = 3306;
  15. $conn = mysqli_connect($hostname, $user, $password, $database, $port);
  16. if (mysqli_connect_errno()) {
  17.     die("Failed to connect to MySQL: " . mysqli_connect_error());
  18. }
  19. mysqli_set_charset($conn,"utf8");
  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 .. WHERE ..");
  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.= '
  31. ';
  32. // loop through database query and fill export variable
  33. while($row = mysqli_fetch_array($query)) {
  34.     // create line with field values
  35.     for($i = 0; $i < $field; $i++) {
  36.         $csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";';
  37.     }
  38.     $csv_export.= '
  39. ';
  40. }
  41. // Export the data and prompt a csv file for download
  42. header('Content-Encoding: UTF-8');
  43. header('Content-type: text/csv; charset=UTF-8');
  44. header("Content-Disposition: attachment; filename=".$csv_filename."");
  45. echo "\xEF\xBB\xBF"; // UTF-8 BOM
  46. echo($csv_export);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top