Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting mysql table to .txt or .doc file using PHP

Tags:

php

mysql

export

I have a mysql table that keeps a log of messages that users send every day. What I want to do is export the the message log once per day into a text file, and am not sure how to do this. Our server has phpmyadmin, and I can export the table into a text file manually, but I don't know how to either A) have phpmyadmin export this file automatically once per day, or B) write the exporting in php code. I want the exported files to be available to the users of my site for download. The site it written in php. If there is any other information you need to answer this question, let me know!

like image 894
user446836 Avatar asked Jul 04 '11 18:07

user446836


1 Answers

<?php
    $fh = fopen('data.txt', 'w');
    $con = mysql_connect("localhost","root","");
    mysql_select_db("db_name", $con);

    /* insert field values into data.txt */

    $result = mysql_query("SELECT * FROM table_name");   
    while ($row = mysql_fetch_array($result)) {          
        $last = end($row);          
        $num = mysql_num_fields($result) ;    
        for($i = 0; $i < $num; $i++) {            
            fwrite($fh, $row[$i]);                      
            if ($row[$i] != $last)
               fwrite($fh, ", ");
        }                                                                 
        fwrite($fh, "\n");
    }
    fclose($fh);
?>
like image 192
anisha Avatar answered Sep 26 '22 23:09

anisha