charlie
charlie

Reputation: 1384

PHP While loop - print data row by row from table

I have a while loop Selecting rows from a database table, and it is printing this data within the while loop:

print $result2["forename"].' '. $result2["surname"].' ('.$result2["email"].')<br><hr />';

But its taking ages to load the page and then displaying loads of rows at once. How can I make it display it row by row as it is loading the data from the database?

Upvotes: 0

Views: 626

Answers (3)

Jakub Matczak
Jakub Matczak

Reputation: 15696

To send buffered data before whole PHP script is executed you can use flush() function. But read the documentation carefully because it may not work in every environment.

Working example:

<?php
header("Content-type: text/html; charset=utf-8");
for ($i = 1; $i <= 10; $i++) {
    print ($i . '<br>');
    flush();
    ob_flush();
    sleep(1);
}

It seems that it's important to send header before. Didn't work without it on my localhost. Also it's good idea to use both flush() and ob_flush() according to flush() documentation.

If still doesn't work

PHP docs says:

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Upvotes: 0

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

Try like

page1.php

<script>
var page=1;
var doRequest = function() {
    $.ajax({
        type:"POST",
        url:"page2.php",
        data:{page:page},
        success: function(response) {
            $("#container").append(response);
            page++;
            doRequest();
        }
    });
}

doRequest();
</script>

<div id='container'>

</div>

page2.php

<?php
$page = $_POST["page"];
$rowsPerRequest = 20;
$offset = ($page - 1) * $rowsPerRequest;

$sql = "SELECT * FROM table LIMIT $offset, $rowsPerRequest";
....
....
print $result2["forename"].' '. $result2["surname"].' ('.$result2["email"].')<br><hr />';

?>

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33542

The PHP is running on the server and outputting the data row by row, but it doesn't send anything to the user until the script has finished processing.

If you are having issues with performance, you might consider trying to tune the query instead, or limit the number of records being returned.

A common trick is to use pagination to pick a bunch of rows, display them qyuckly and then re-query the database if needed to get the next bunch. Generally this allows for a much smaller footprint and the user can choose if they want to actually view additional results.

Upvotes: 1

Related Questions