down321
down321

Reputation: 39

How to put each result of a MySQL query into a text file one by one?

while($row= mysql_fetch_object($result)){
    $row->products_price=$row->products_price-($row->products_price*0.05);
    echo $row->products_id ." ". $row->products_price."<br/>";
}

How can I put $row->products_id ." ". $row->products_price into a txt file with one row a time?

Upvotes: 0

Views: 105

Answers (2)

noob
noob

Reputation: 9202

$content = "";
while ( $row = mysql_fetch_object($result) ){
    $row->products_price = $row->products_price-($row->products_price * 0.05);
    $content .=  $row->products_id . " " . $row->products_price . "\r\n";
}
file_put_contents("filename.txt", $content, LOCK_EX);

Edit: (a version for Hikaru-Shindo)

while ( $row = mysql_fetch_object($result) ){
    $row->products_price = $row->products_price-($row->products_price * 0.05);
    file_put_contents("filename.txt", $row->products_id . " " . $row->products_price . "\r\n", FILE_APPEND | LOCK_EX);
}

Upvotes: 3

craig1231
craig1231

Reputation: 3867

$fh = fopen("myfile.txt", "w+");
while($row= mysql_fetch_object($result))
{
    $row->products_price=$row->products_price-($row->products_price*0.05);
    fwrite($fh, $row->products_id ." ". $row->products_price."\r\n");
}
fclose($fh);

Upvotes: 0

Related Questions