-2

i am trying to make a program that syncs all the outcome of a row in my mysql database to a .txt file. But it doesnt work. I want each result on a new line.

This is my code:

<?php
$db = mysqli_connect("localhost", "username", "pass", "database");


$hwid_query = "SELECT hwid FROM users";
$result = mysqli_query($db, $hwid_query);
//$hwids = mysqli_fetch_assoc($result);


while($row = mysqli_fetch_assoc($result)){
$hwids = $row['hwid'];
echo $hwids;
}


$fp = fopen('lt.txt', 'w');
ftruncate($fp, 0);
fwrite($fp, $hwids);
fclose($fp);
mysqli_close($db);
?>

This results in one line in the file with only one of the columns of the database, while echo $hwids; gives all of them. What am i doing wrong?

legoscia
  • 39,593
  • 22
  • 116
  • 167
  • The reason you get downvotes is because you miss the "What have you tried?" part. Try to figure out *why* it doesnt work. This is a difficult to learn skill, but after practising a valueable one as it helps debugging later on in your progress. – Martijn Nov 23 '18 at 08:12

1 Answers1

2

In the while loop you set $hwids to that rows value. The next itteration (eg the next row from the DB) overwrites that same $hwids to it's value, it overwrites it. At the end of the while, you have the last entry from your result.

There are a few solutions, but in the one below, I write the value to the file per itteration:

$file = fopen('lt.txt', 'wb');
while($row = mysqli_fetch_assoc($result)){
    $lineToAdd = $row['hwid'] . PHP_EOL; // PHP_EOL = "\n" = Newline
    fwrite($file, $lineToAdd);
}
fclose($file);

I've based this upon this answer

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • Thanks! Why does everyone disrate my questions? – Nonstop Youtuber Nov 23 '18 at 08:08
  • I've answered that under your question. On this site, when an posted answer is the solution to a problem, it's normal to mark it as such, so that other people can easily spot the solution when they have the same issue. – Martijn Nov 23 '18 at 08:13