How to save while result to txt file?

Asked

Viewed 563 times

-2

Generates txt, but saves only the last entry of the database and in the precise case of all data.

$querymail = mysql_query("select mat,nome from usuario ");

while($data = mysql_fetch_array($querymail)) {
    $log = str_pad($data[0], 10, "0", STR_PAD_LEFT);
    $log1 = str_pad($data[1], 40, " ", STR_PAD_RIGHT);

    $linhas = "log1$log2.";         
}
    1. No longer use the functions mysql_*, they are obsolete. 2) Search about the function fwrite. 3) One was missing $ in the variable $conexao in the last row.
  • 2

    Possible duplicate of Write to txt file with PHP

  • It’s not duplicated, different situations.

  • Do the indicated search, try to make a solution and if you get an error, go back and edit the question with the code and the error message. Use the question that Daniel indicated as study material as well. It has the solution you need, just analyze the code.

  • I made the suggestion, but the problem persists...

1 answer

1


The file_put_contents command writes a string to a file, if this file does not yet exist it creates the file

    while($data = mysql_fetch_array($querymail)) {
       $log = str_pad($data[0], 10, "0", STR_PAD_LEFT);
       $log1 = str_pad($data[1], 40, " ", STR_PAD_RIGHT);

        $linhas .= $log. " " .$log1."\n";         
    }

file_put_contents('arquivo.txt', $linhas);

If you just want to add a value in an already created file, you will have to use a third parameter with the value FILE_APPEND, so:

file_put_contents('arquivo.txt', $linhas, FILE_APPEND);
  • Leo, implemented his solution keeps appearing only one line, would have another orientation?

  • how many lines this while returns?

  • the goal is to return all data from the table, in this case about 200 records

  • $lines .= $log. " " . $log1." n"; accumulates all this data is the same as $lines = $lines . $log. " " . $log1." n";

  • I did a new test implementing your orientation and it worked as follows. The file generated on the server contains all the data and what is being downloaded continues with a line.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.