Search code examples
phpmysqlfopenfwrite

Resource id #7 when using fopen and fwrite in PHP


I'm trying to create a download link in PHP so you can download the information in a table. I just started writing it and have run into a snag. Here is what I have so far:

 <?php
 $sql = "SELECT * FROM " . $survey . ";";
 $result = mysql_query($sql)
    or die(mysql_error());
 $row = mysql_fetch_assoc($result);


 $something = "This is text";
 $myFile = "data.txt";
 $fh = fopen($myFile, 'w') or die("can't open file");

 $download_data = "";
 foreach ($row as $k=>$v){
        $download_data .= $k . "=" . $v . "\n";
 }
 fwrite($fh, $download_data);
 fclose($fh);

 echo $download_data;

 ?>
 <a href="data.txt">Download </a>

It is just supposed to show something like Code = 1 Name = John etc. When I open the txt file, it simply says Resource id #7. The weird part is, when I echo $download_data, it looks correctly in the web page. Is there something special I have to do with fwrite in order to get the whole string into the text file

(Note: I have used both mysql_fetch_array and mysql_fetch_assoc and both have the same result. Also, if I simply declare a variable like $test = "this is a test"; it works).

Edit: I have tried commenting out all other code in the script and I get the same result. Printing $download_data shows the right result, but the text file is still only showing Resource id #7. I've even tried deleting the txt file and when it is recreated, it does the same thing.


Solution

  • You're almost certainly not showing us the whole picture with your example code.

    You are likely writing one of these things to the file:

    1. The file handle, $fh
    2. The result returned from mysql_query()

    Check you're not mixing up $result and $row. Or even better, post all of your code.