Search code examples
phpsearch-engine

php paging script for a search engine


i have a paging script

for($page = 1; $page <= $maxPage; $page++)
{
   if ($page == $pageNum)
   {
      $nad .= " $page "; // no need to create a link to current page
   }
   else
   {
      $nad .= " <a href=\"/search?search&q=".$_GET["q"]."&page=$page\">$page</a> ";
   }
}

that will show pages for the search query. I want to limit the amount of pages it shows to 5, because currently it shows every page, which is a problem,
say if there were 5000 rows and 5 rows per page, it would show 1000 pages. How do i limit that to 5?


Solution

  • You can use the min() and the max() functions:

    $firstPage = max(1, $pageNum-5);
    $lastPage = min($maxPage, $pageNum+5);
    for($page = $firstPage; $page <= $lastPage; $page++)
    {
      // no changes here
    }