Guest User

Untitled

a guest
Sep 9th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. <?php
  2.  
  3. /*** mysql hostname ***/
  4. $hostname = 'localhost';
  5.  
  6. $dbname = 'dbname';
  7.  
  8. /*** mysql username ***/
  9. $username = 'username';
  10.  
  11. /*** mysql password ***/
  12. $password = 'password';
  13.  
  14. try {
  15. $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
  16.  
  17. $tablename = 'table';
  18.  
  19. $sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
  20.  
  21. $stmt = $dbh->query($sql);
  22. $stmt->execute();
  23.  
  24. while($row = $stmt->fetch(PDO::FETCH_ASSOC))
  25. {
  26. array_push($fields, $row['Field']);
  27. }
  28.  
  29. array_push($csv, $fields);
  30.  
  31. $sql = 'SELECT * FROM `'.$tablename.'`';
  32.  
  33.  
  34. $stmt = $dbh->query($sql);
  35. $stmt->execute();
  36.  
  37. $csv = array();
  38.  
  39. while($row = $stmt->fetch(PDO::FETCH_NUM))
  40. {
  41. array_push($csv, $row);
  42. }
  43.  
  44. $fp = fopen('file.csv', 'w');
  45.  
  46. foreach ($csv as $row) {
  47. fputcsv($fp, $row);
  48. }
  49.  
  50. fclose($fp);
  51.  
  52. header("Content-type: application/csv");
  53. header("Content-Disposition: attachment; filename=export.csv");
  54. header("Pragma: no-cache");
  55. header("Expires: 0");
  56.  
  57. readfile('file.csv');
  58.  
  59. $dbh = null;
  60.  
  61. } catch(PDOException $e) {
  62. echo $e->getMessage();
  63. }
Add Comment
Please, Sign In to add comment