user2014429
user2014429

Reputation: 2577

set maximum pagination links

I have a large database which can yield thousands of results and I need to limit the amount of pagination links of say 9 links, with previous 4 pages on one side then the current page then the 4 next pages.

for example: 14|15|16|17|18|19|20|21|22 anyone know how I could achieve this? Thanks

if (isset($_GET["page"])) 
  { 
    $page  = $_GET["page"];
  } 
    else 
  { 
    $page=1; 
  };

$start_from = ($page-1) * 10;
$message =  "SELECT * FROM document WHERE email='$_SESSION[email]' ORDER BY id DESC LIMIT $start_from , 10";

          // echo  results

         // make page links for results

  $sql = "SELECT id FROM document WHERE email = '$_SESSION[email]'";
  $rs_result = $db->query($sql);
  $total_records = $rs_result->num_rows;
  $total_pages = ceil($total_records / 10);

  if($rs_result->num_rows >10) {

$page = "<p class = 'page'>";
  for ($i=1; $i<=$total_pages; $i++) 
 {
   $page .="<a href='results.html?page=".$i."'>".$i."</a> ";
 }
   $page .="</p>";
   echo $page;
}

Upvotes: 0

Views: 278

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

Just use basic math to calculate the start and end pages for use in your loop:

$page_range_offset = 4;    
$page_start = $page - $page_range_offset;    
if ($page_start < 1) {
    $page_start = 1;
}    
$page_end = $page + $page_range_offset;
if ($page_end > $total_pages) {
    $page_end = $total_pages;
}

for ($i=$page_start; $i<=$page_end; $i++) {
   $page .="<a href='results.html?page=".$i."'>".$i."</a> ";
}

Upvotes: 2

Related Questions