Kavya Shree
Kavya Shree

Reputation: 1032

How to create simple pagination in PHP page

Below is my Code.

<?php

$folder_name=$_GET['folder_name'];
$dirname = "customized_kits/images/";

$images = glob($dirname."*");
 $filecount = count( $images );
$i=0;

for($i=0;$i<200;$i++) { ?>
    <div class="col-md-2">  <div class="photos">
        <div id="images1">
            <a href=# data-lightbox="roadtrip">
            <?php
            if($filecount>$i) {
                $filename = substr($images[$i], strrpos($images[$i], '/') + 1);   
    echo '<a href="'.$images[$i].'" target="_blank"><img src="'.$images[$i].'" style="width:150px;height:150px" /></a><br/>';
            ?>

            <a href="#" class="del_photo1" style="color:#C20B0B;font-size:20px;" onclick="theFunction('<?php echo $filename; ?>','<?php echo $folder_name; ?>');"><i class="fa fa-remove"></i></a>

            <?php } else {
                echo '<a ><img style="width:150px;height:150px;background-color:#eee" /></a>';
            } ?>

            </div>
        </div>
    </div>
    <?php } ?>

Here I created 200 boxes with foreach loop I want to show 20 divs for single page and with help of pagination I want to show other divs.I searched in many websites I didnt get exact answer please help me to get out of this issue.

Upvotes: 0

Views: 224

Answers (1)

georoot
georoot

Reputation: 3617

Okay so from your code you can have 200 values of $i and you want to paginate them in segments of 20. Let us start off by adding a script above your code to get the range that needs to be displayed. Page number comes as a GET parameter in number. ex example.com/feeds?number=2.

<?php
$pageno = $_GET['number']; // Page number from frontend
// Now this value will give you 1,2,3 etc
$start = $pageno*20;
// $start contains the initial offset or the value of `$i` from to start
for($i=$start;$i<$start+20;$i++) {
    // Will only show 20 elements on the page
}
?>

Remember this is a very basic example. Although i would recommend using range in sql query instead so you don't have to load the complete dataset in each query.

More explanation

Suppose you have M results and you want to show N results on each page, the results on page x would start from x*N to x*(N+1) pure math here. In your code you are iterating $i over the whole loop rather just iterate over that specific range to get results. The value of x is the example is the page number that we get from number in GET verb.

Upvotes: 1

Related Questions