www.webdeveloper.com
Results 1 to 3 of 3

Thread: MySQL dump to spreadsheet file

  1. #1
    Join Date
    Nov 2002
    Posts
    421

    MySQL dump to spreadsheet file

    I am trying to get some generic code to work, which will take a table and dump the elements into a tab delimited file that can then be opened in a spreadsheet.

    I think I am getting close with this:

    Code:
    $query = mysql_query("SELECT * FROM `members`");
    while ($row = mysql_fetch_array($query)) {
      foreach ($row as $element) $output .= $element."\t";	
      $output .= "\r\n";
      @file_put_contents($file,$output,FILE_APPEND|LOCK_EX);
      unset($output);
    }
    It works except each row in the file has each element twice. I don't see how that is happening. All the elements are there and all the rows are in separate lines as I want. But each line has each element value twice.

    The other thing I would like to do is have a first row with the element name. I figure that would take another query initially as the first line in the output file, then start over with the code above. But I am not sure how to extract the element names in the row.

    Any help would be greatly appreciated.

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,637
    I would recommend outputting it as a CSV file. (If you really need to have tabs, just use the optional 3rd arg of fputcsv() to use "\t" as the delimiter.)

    Untested:
    PHP Code:
    $fh fopen($file'w');
    if(
    $fh == false) {
       die(
    'fopen problem');
    }
    $row mysql_fetch_assoc($query);
    fputcsv($fharray_keys($row)); // print column names
    mysql_data_seek($query0); // back to first record
    while($row mysql_fetch_assoc($query)) {
       
    fputcsv($fh$row);
    }
    fclose($fh); 
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Nov 2002
    Posts
    421
    Works perfect. Thank you.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles