简体   繁体   中英

How to display long while/for loop in pagination?

I have a while/for loop with thousands results. Since it contains several fields, I use table to display it. However, with thousands results being displayed at the same time, it will definitely slow down the performance. How can I display it in pagination?

    <table>
    <?php $count = 1000;
    for($a=1;$a<=$count;$a++) { ?>
        <tr>
            <td><?php echo $a; ?></td>
            <td>This is number <?php echo $a; ?></td>
        </tr>
    <?php $i++; 
    } ?>
    </table>

If the data comes from a database you can limit the result set. If you are using MySQL you use the LIMIT clause. This will allow you to only fetch the specified number of rows.

SELECT title, description FROM posts LIMIT 25

This will only fetch 25 rows. Then if you want to fetch the results after row 25 you can provide an offset. This is done a little different since the offset comes first in the LIMIT clause. Only one argument is provided MySQL assumes its the limit instead. To select the next 50 rows you use.

SELECT title, description FROM posts LIMIT 25, 50

This can be useful to reduce the result set fetched and help increase performance/load times due to a smaller amount of data that needs to be processed.

I hope this can help you, happy coding!

Update

This is a little tutorial in using the LIMIT clause in MySQL

My only solution without having a DB with the data would be to pass the array key you are on to the next page. For example:

$start = 1;
$end = 1000;
if(isset($_GET['record_number'])){
    $start = $_GET['record_number'];
    $end = $_GET['record_number'] + 1000;
}

for($a=$start; $a<=$end; $a++){
    //code here
}

Other than that, you might consider creating a list of files in a DB engine so you can use the LIMIT parameter.

Here is my example, it's similar to the answer from @AnotherGuy

<form method="GET">
<input type="text" name="rowsPerPage">
<?php
    for($i = 1; $i+1 < $count/$rowsPerPage; $i++){
        echo '<input type="submit" name="page" value="'.$i.'">';
    }
?>
</form>


<?php
    $begin = (int)$_GET['rowsPerPage']*$_GET['page'];
    $take = (int)$_GET['rowsPerPage'];
    $sql = "SELECT ... LIMIT {$begin}, {$take}";
?>

It's possible that the code contains "typos", but I hope it will give you new ideas.

I would recommend you to use GET instead of POST. GET will be saved in the URL, in this way, it will be easier to reload the page without losing the page-settings.

www.example.com?rowsPerPage=150&page=2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM