0

I currently have an app that displays about 4,000 items. I am pulling this from a mysql database. I am trying to create a button that will force a download of all of the items from the database into a csv file. How can I go about this?

csv.php

<?php

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

$output = fopen('php://output', 'w');

fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

mysql_connect('localhost', 'root', 'root');
mysql_select_db('wp_xroads');
$rows = mysql_query('SELECT first_name,last_name,phone FROM bags');

while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
?>

html

<div class="col-md-2">
  <!-- Button to trigger csv file exporting -->
    <form action="csv.php" method="get">
        <a class="btn btn-success" type="submit" target="_blank">
          Export CSV <span class="badge"><span class='glyphicon glyphicon-save-file'></span></span>
        </a>
    </form>
</div>

thanks in advance. -ken

Ken Ryan
  • 437
  • 1
  • 7
  • 24

1 Answers1

2

the SELECT INTO OUTFILE is the opposite of LOAD DATA FILE. This puts the results of the select statement into the specified file. No slow, zanny, non-performant php looping. The export_options clause is in the same flavor of the options in LOAD DATA INFILE.

https://dev.mysql.com/doc/refman/5.1/en/select-into.html

SELECT col1,col2,col3 INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;


SELECT first_name,last_name,phone INTO OUTFILE '/tmp/myBags.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM bags;
Drew
  • 24,120
  • 9
  • 38
  • 72