Jump to content

[SOLVED] fwrite() with mysql_fetch_array issue


Janco

Recommended Posts

Hi all,

I hope that someone can help with this one?

 

My code:

<--------------- snip ----------------->

while ($row=mysql_fetch_array($result)) {

$var1=$row['col1'];

$var2=$row['col2'];

$var3=$row['col3'];

.

.

.

$var78=$row['col78'];

 

// write output of the array to a file

 

$file = "FILE";

$fo = fopen($file, 'w');

$string = "$var1,$var2,$var3,.........,$var78\n"

fwrite($fo, $string);

fclose($fo);

}

>?

 

<------------- snip ------------------->

 

The array is fetched but when it is written to the file the rows aren't appended but overwritten and I end up with only the last row's data in the file.

 

The idea is that a bash script in the cron calls the PHP script and then the file is distrobuted to several sites.

 

I've tried using the MySQL "OUTFILE" option but then I had to add a lot more functions to bash script to prep the file i.e. padding and special delimiters and sed and awk could really do what I needed but with the PHP the prepping is so much easier, quicker, a lot less coding and less complicated.

 

Can anyone point out what I'm doing wrong, why isn't the row data being appended but overwritten instead?

 

Thank you in advance.

<?php

$file = "FILE";
$fo = fopen($file, 'a');

while ($row=mysql_fetch_array($result)) {
$var1=$row['col1'];
$var2=$row['col2'];
$var3=$row['col3'];
$var78=$row['col78'];

// write output of the array to a file
$string = "$var1,$var2,$var3,.........,$var78\n"
fwrite($fo, $string);
}

fclose($fo);
?>

 

Its bad to open/close a file many times.

 

Use 'a' instead of 'w' for the fopen mode to append the text to the bottom.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.