Christian K.
Christian K.

Reputation: 538

Output Text in PHP While Loop (while page is still working?)

I have a simple php page, that is doing some operations for an mysql result set:

$i = $d = $n = 0;

$sql="SELECT record, field1,field2,field3 from table where condition='xxxx'" ;
result=$db->send_sql($sql);

while($row=mysql_fetch_array($result, MYSQL_ASSOC))
{
  //about 500 results
  //now performing some actions on these results via function call
  $i++;
  if($row['field1'] == 'xxx')
  {
    $d++;
    echo $row['record'].": ";
    echo do_something(field1,field2); //function will echo some text
    echo "<br>";
  }
  else
  {
    $n++;
    echo $row['record'].": nothing to do <br>";
  }
}
echo "<hr>Total: ".$i." - Updates: ".$d." - Nothing done: ".$n;

All works, as it should but the Output/echos are only shown, once all operations have been done and the while statement has been worked through.

It might be a silly question, but is there a way to show the "echos/output" "on the fly" - so the user get's the "something is happening" experience?

Upvotes: 0

Views: 585

Answers (3)

bishop
bishop

Reputation: 39494

echo sends the output toward the user immediately, but that output might be held up by a couple of layers in between. If you want the feel you describe, use AJAX. Otherwise, you can try some of these approaches:

  • Turn output buffering off
  • flush() immediately after sending your HTML head element
  • then flush() periodically, with some str_repeat() to kickstart/prevent timeouts

See also this and this conversation on performance/best practices and this conversation on output buffering.

Upvotes: 1

Elon Than
Elon Than

Reputation: 9775

You can try to use flush() function to send data to browser after each loop execution.

Upvotes: 0

CoryClough
CoryClough

Reputation: 11

PHP is run on the server and displays output to the client when it is finished. I think you will need Javascript to do this, but I could be wrong.

Upvotes: 1

Related Questions