Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2011
    Posts
    3

    Unanswered: 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.

  2. #2
    Join Date
    May 2008
    Posts
    277
    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);

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •