Can't write SQL query results to a file with PHP

I have a script that creates a file but then fails to write to it. The content to be written is an SQL query result.

The DB connection is fine.
The query is fine; I can echo the results to the screen.
The file IS created on the server.
I have permission to write to it; when I run the deprecated mysql version of my script, it writes to the file perfectly.
My script doesn’t fail on the $ret flag below, but it writes 0 bytes. The file itself looks entirely blank when I open it on the server, or download and open it.

The code is:

 $stmt1 = $db->prepare("SELECT .  blah blah . . ");  
 $stmt1->execute();
 $row = $stmt1->fetch(PDO::FETCH_ASSOC);
    $fh = fopen('myfile.txt', 'wb');
       while ($row = $stmt1->fetchAll(PDO::FETCH_ASSOC)) 
         {          
            $last = end($row);          
            $num = $stmt1->columnCount();    
               for($i = 1; $i < $num; $i++) 
                 {            
                   fwrite($fh, $row[$i]);                      
                   if ($row[$i] != $last)
                   fwrite($fh);
                 }                                                                 
            $ret = fwrite($fh, "\r\n");
        }
        fclose($fh);

    if ($ret === false)
      die("Fwrite failed");
    echo ("fwrite wrote $ret bytes");

I’ve tried fetch() instead of fetchAll(); the script then writes 2 bytes, but the file is blank on inspection.
I’ve also tried other write parameters than ‘wb’. To no avail.

FYI, the deprecated code that works fine is:

$fh = fopen('myfile.txt', 'wb');
 
    while ($row = mysql_fetch_array($result)) 
     {          
        $last = end($row);          
        $num = mysql_num_fields($result) ;    
           for($i = 1; $i < $num; $i++) 
             {            
               fwrite($fh, $row[$i]);                      
               if ($row[$i] != $last)
               fwrite($fh);
             }                                                                 
        fwrite($fh, "\r\n");
      
     }
    fclose($fh);

Any help much appreciated!

I solved the problem. I got rid of fetch assoc in the while loop. The code that works is:

while ($row = $stmt1->fetch())
{

Sponsor our Newsletter | Privacy Policy | Terms of Service