If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > PHP > Export mysql results to CSV from PHP website

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-26-11, 00:33
labhijitp labhijitp is offline
Registered User
 
Join Date: Apr 2011
Posts: 3
Export mysql results to CSV from PHP website

I have written a small (2line) query. I want to create link on my php site which on click will run this script automatically and export results to an excel or csv file. I dont want to create a page to view the results.

Any help to this new bie will be very useful. I am not well conversed with PHP just know a little bit of mysql.
Reply With Quote
  #2 (permalink)  
Old 04-29-11, 13:09
futurity futurity is offline
Registered User
 
Join Date: May 2008
Posts: 270
PHP Code:
<?php

// fetch data from database
$db mysqli_connect();
$result mysqli_query($db'select * from mytable');

// send http headers
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="example.csv"');

// get file pointer to stdout
$fp fopen('php://output''wb');

//output header line and first row
$row mysqli_fetch_assoc($result);
fputcsv($fparray_keys($row));
fputcsv($fp$row);

// output remaining rows
while ($row mysqli_fetch_row($result)) {
    
fputcsv($fp$row);
}

fclose($fp);
Reply With Quote
Reply

Tags
csv, mysql, php

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On