reenadak

export mysql to csv

Sep 25th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. $database="tutorial";
  2. $table="name_list";
  3. mysql_connect("localhost","","");
  4. mysql_select_db("tutorial");
  5.  
  6. $result=mysql_query("select * from $table");
  7.  
  8. $out = '';
  9.  
  10. // Get all fields names in table "name_list" in database "tutorial".
  11. $fields = mysql_list_fields(tutorial,$table);
  12.  
  13. // Count the table fields and put the value into $columns.
  14. $columns = mysql_num_fields($fields);
  15.  
  16. // Put the name of all fields to $out.
  17. for ($i = 0; $i < $columns; $i++) {
  18. $l=mysql_field_name($fields, $i);
  19. $out .= '"'.$l.'",';
  20. }
  21. $out .="n";
  22.  
  23. // Add all values in the table to $out.
  24. while ($l = mysql_fetch_array($result)) {
  25. for ($i = 0; $i < $columns; $i++) {
  26. $out .='"'.$l["$i"].'",';
  27. }
  28. $out .="n";
  29. }
  30.  
  31. // Open file export.csv.
  32. $f = fopen ('export.csv','w');
  33.  
  34. // Put all values from $out to export.csv.
  35. fputs($f, $out);
  36. fclose($f);
  37.  
  38. header('Content-type: application/csv');
  39. header('Content-Disposition: attachment; filename="export.csv"');
  40. readfile('export.csv');
Add Comment
Please, Sign In to add comment