Advertisement
Guest User

Untitled

a guest
Sep 13th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. exportMysqlToCsv('export_csv.csv');
  5.  
  6.  
  7.  
  8. function exportMysqlToCsv($filename = 'export_csv.csv')
  9. {
  10.  
  11. $conn = dbConnection();
  12.  
  13. if ($conn->connect_error) {
  14. die("Connection failed: " . $conn->connect_error);
  15. }
  16. $sql_query = "SELECT * FROM cadastros";
  17.  
  18.  
  19. $result = $conn->query($sql_query);
  20.  
  21. $f = fopen('php://temp', 'wt');
  22. $first = true;
  23. while ($row = $result->fetch_assoc()) {
  24. if ($first) {
  25. fputcsv($f, array_keys($row));
  26. $first = false;
  27. }
  28. fputcsv($f, $row);
  29. } // end while
  30.  
  31. $conn->close();
  32.  
  33. $size = ftell($f);
  34. rewind($f);
  35.  
  36. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  37. header("Content-Length: $size");
  38. header("Content-type: text/x-csv");
  39. header("Content-type: text/csv");
  40. header("Content-type: application/csv");
  41. header("Content-Disposition: attachment; filename=$filename");
  42. fpassthru($f);
  43. exit;
  44.  
  45. }
  46.  
  47. // db connection function
  48. function dbConnection(){
  49. $servername = "localhost";
  50. $username = "root";
  51. $password = "";
  52. $dbname = "creche_escolas";
  53. // Create connection
  54. $conn = new mysqli($servername, $username, $password, $dbname);
  55. return $conn;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement