I have a pagination script with PHP. When page records are some hundreds, the pagination result is too big. How I can limit the page numbers/links?
Example: < 1 | 2 ... 37 | 38 | 39 | 40 | 41 | 42 ... 82 | 83 >
This is my PHP script
<?php
$ppp = 10;
$rows = mysql_num_rows($query);
$nmpages = ceil($rows/$ppp);
// if current page is not 1, draw PREVIOUS link
if ($pg > 1 && $nmpages != 0) {
echo "<a href=\"?pg=".($pg-1)."\"><</a> ";
}
For($i = 1 ; $i <= $nmpages ; $i++) {
If($i == $pg) {
echo "<a href=\"#\" class=\"selected\"><b>".$i."</b></a> ";
} else {
echo "<a href=\"?pg=".$i."\">".$i."</a> ";
}
}
// if current page less than max pages, draw NEXT link
if ($pg < $nmpages && $nmpages != 0) {
echo "<a href=\"?pg=".($pg+1)."\">></a>";
}
?>
Do you have an ideas how I can do this with the specific PHP script that I have?
Try this :
<?php
$link = "";
$page = $_GET['pg']; // your current page
// $pages=20; // Total number of pages
$limit=5 ; // May be what you are looking for
if ($pages >=1 && $page <= $pages)
{
$counter = 1;
$link = "";
if ($page > ($limit/2))
{ $link .= "<a href=\"?page=1\">1 </a> ... ";}
for ($x=$page; $x<=$pages;$x++)
{
if($counter < $limit)
$link .= "<a href=\"?page=" .$x."\">".$x." </a>";
$counter++;
}
if ($page < $pages - ($limit/2))
{ $link .= "... " . "<a href=\"?page=" .$pages."\">".$pages." </a>"; }
}
echo $link;
?>
OUTPUT :
//At page=1
1 2 3 4 ... 20
//At page=12
1 ... 12 13 14 15 ... 20
//At page=18
1 ... 18 19 20
An improvement or rather re-write based on @Makesh's code.
function get_pagination_links($current_page, $total_pages, $url)
{
$links = "";
if ($total_pages >= 1 && $current_page <= $total_pages) {
$links .= "<a href=\"{$url}?page=1\">1</a>";
$i = max(2, $current_page - 5);
if ($i > 2)
$links .= " ... ";
for (; $i < min($current_page + 6, $total_pages); $i++) {
$links .= "<a href=\"{$url}?page={$i}\">{$i}</a>";
}
if ($i != $total_pages)
$links .= " ... ";
$links .= "<a href=\"{$url}?page={$total_pages}\">{$total_pages}</a>";
}
return $links;
}
OUTPUT:
page = 1
1 2 3 4 5 6 ... 20
page = 10
1 ... 5 6 7 8 9 10 11 12 13 14 15 ... 20
page = 19
1 ... 14 15 16 17 18 19 20
The answer for this question was basically to visit a page about Digg style pagination which includes code samples.
So that's the answer, but this question is basically a duplicate.
Try to make a page bracket for example 10 less and 10 more than the actual page, change for example the for statement for this:
For($i = $pg-10 ; $i <= $pg+10 ; $i++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With