Instead of printing hundreds of page links, show a small window around the current page and always provide access to the first and last pages.
<?php
$currentPage = max(1, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1);
$totalPages = max(1, (int) ceil($totalRecords / $perPage));
$currentPage = min($currentPage, $totalPages);
$window = 2;
$from = max(1, $currentPage - $window);
$to = min($totalPages, $currentPage + $window);
for ($page = $from; $page <= $to; $page++) {
if ($page === $currentPage) {
echo '<strong aria-current="page">' . $page . ' ';
} else {
echo '<a href="?page=' . $page . '">' . $page . '</a> ';
}
}
?>
This produces compact navigation even when the result set contains many pages. The original two-level paging logic remains below for comparison.
https://www.plus2net.com/php_tutorial/demo_paging1.php?start=20
In advanced script it is
https://www.plus2net.com/php_tutorial/php_paging_adv.php?start=12&p_f=8
We are sending one extra variable in advanced script. However based on the value of the variable start the records are displayed. But here bottom links records are not displayed till the end, it only display links up to the next higher group. You can see link groups are created in two levels, one link group is higher group or outer one and one is within group or inner link group.
if($p_f<>0){print "<a href='$page_name?start=$p_back&p_f=$p_back'><font face='Verdana' size='2'>PREV $p_limit</font></a>"; }
This link will be visible if $p_f value is not equal to zero , that mean this link will not be displayed at the starting. Now once this link is clicked it will carry the new value of $p_f which is present value minus the jump value of outer group. This value of $p_back is set like this before. $p_back=$p_f-$p_limit;
In the same way the Next link of outer group is displayed. Here before the link the value of $p_fwd is calculated like this.
$p_fwd=$p_f+$p_limit;
Now with this value of $p_fwd there will be jump for the outer group links to next value. Here is the link
print "<a href='$page_name?start=$p_fwd&p_f=$p_fwd'><font face='Verdana' size='2'>NEXT $p_limit</font></a>";
for($i=$p_f;$i < $nume and $i<($p_f+$p_limit);$i=$i+$limit){
}
We have left the internal linking structure inside the for loop as it is same as the basic script. Just read how the for loop in the above code is designed.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.