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
  • 539
  • 1
  • 10
  • 31

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,851
  • 10
  • 43
  • 78
  • just left ya a comment (notice his * and from) @BK435 – Drew Jul 20 '15 at 23:51
  • hey @drew-pierce, Is what you provided the query I would be using to get the csv file? would I just link the php file to an tag? Thanks for your help. – Ken Ryan Jul 20 '15 at 23:53
  • Check out bottom of edit above. how you call it is up to you (remember, they are writing to your file system :<). But it could be in a protected area somewhere in your app. Just about anywhere. So you want this to be more of an admin rights thingie. – Drew Jul 20 '15 at 23:57
  • That select statement can be as complicated as you want. It can be a huge join, computed columns, you name it. – Drew Jul 20 '15 at 23:58
  • Let me give it a try :) thank you – Ken Ryan Jul 21 '15 at 00:00