Write Mysql results to a text file

Discussion in 'PHP' started by meannn, Feb 1, 2010.

  1. #1
    Hello mates, I need help about writing mysql results to a text file. I stuck in this code, it only write "array" to a text file. :(

    $myFile = "test.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    
    function data_dump( $query ) {
        $results = mysql_query( $query );
    
        $data = array();
    
        while ( $row = @mysql_fetch_assoc( $results ) )
            $data[] = $row;
    
        return $data;
    }
    
    $stringData = data_dump( $query )."\n";
    
    fwrite($fh, $stringData);
    fclose($fh);
    PHP:
     
    meannn, Feb 1, 2010 IP
  2. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #2
    If you want to read it back into the variable later, use serialize(). If you just want to store the contents for someone to look at, use join() with a friendly delimiter like ' | '.
     
    SmallPotatoes, Feb 1, 2010 IP
  3. swarg

    swarg Peon

    Messages:
    105
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    ESCAPED BY ‘\\’
    LINES TERMINATED BY '\n'
    FROM users WHERE 1

    It's an example, update the query in it
     
    swarg, Feb 1, 2010 IP
  4. javaongsan

    javaongsan Well-Known Member

    Messages:
    1,054
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #4
    Try this
    
    $myFile = "test.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    
    while ($result = mysql_fetch_row($query)) 
    {			
    	$str='';
    	foreach($result as $value)
    	{			
    		if ($value=== NULL OR is_null($value))
    				$value = 'NULL' ;
    		$str= $str.$value.',';
    	}
    	fwrite($fh, $str."\n");		
    }
    fclose($fh);
    
    Code (markup):
     
    javaongsan, Feb 1, 2010 IP