Paginator (page navigation)


/ Published in: PHP
Save to your folder(s)

This function build page navigation links.\r\nParameters legend:\r\n- $items = total number of rows to be paginated\r\n- $perpage = how many rows to be displayed on a page\r\n- $maxlinks - how much page links to be build and shown for navigation ( < 1 2 3 4 5 > )


Copy this code and paste it in your HTML
  1. function paginator($items, $perpage = 10, $maxlinks = 10) {
  2. $delitel = $maxlinks;
  3. $totalpages = ceil($items / $perpage);
  4. if(isset($_GET['page']) && is_numeric($_GET['page'])) {
  5. $page = $_GET['page'];
  6. }
  7. else {
  8. $page = 1;
  9. }
  10.  
  11. if($items != 0 && $page >= 1 && $page <= $totalpages) {
  12. if($totalpages > 0 && $totalpages <= $maxlinks) {
  13. $maxlinks = $totalpages;
  14. $c = 1;
  15. }
  16. else {
  17. $c = $page;
  18. $min = floor($maxlinks /2);
  19. $max = $totalpages - $min;
  20.  
  21. if(($page > $min) && ($page < $max)) {
  22. $c = $page - $min;
  23. }
  24. elseif($page > $min && $page >= $max) {
  25. $c = $max;
  26. }
  27. else {
  28.  
  29. $c = 1;
  30. }
  31. }
  32.  
  33. $link = '';
  34. if(isset($_SERVER['PATH_INFO'])) {
  35. $link .= $_SERVER['PATH_INFO'];
  36. }
  37. $link .= '?';
  38. foreach($_GET as $g => $v) {
  39. if($g != 'page') {
  40. $link .= $g.'='.$v.'&';
  41. }
  42. }
  43.  
  44. $out = '';
  45. if($totalpages != 1 && $page != 1) {
  46. $out .= "<a class=\"page\" href=\"".$link."page=1\"><span>First page</span></a>";
  47. }
  48. if($page != 1) {
  49. $out .= "<a class=\"page\" href=\"".$link."page=".($page - 1)."\"><span>&laquo;</span></a>";
  50. }
  51.  
  52. for($i=1; $i <= $maxlinks; $i++) {
  53. if($c <= $totalpages && $totalpages != 1) {
  54. if($c == $page) {
  55. $out .= "<a class=\"current\" href=\"".$link."page=".$c."\"><span>".$c."</span></a>";
  56. }
  57. else {
  58. $out .= "<a class=\"page\" href=\"".$link."page=".$c."\"><span>".$c."</span></a>";
  59. }
  60. $c++;
  61. }
  62. }
  63. if($totalpages == 1) {
  64. $out .= '<a href="#" class="current"><span>Page 1 of 1</span></a>&nbsp;';
  65. }
  66. if($page != $totalpages && $page < $totalpages) {
  67. $out .= "<a class=\"page\" href=\"".$link."page=".($page + 1)."\"><span>&raquo;</span></a>&nbsp;";
  68. }
  69. if($totalpages != 1 && $page != $totalpages) {
  70. $out .= "<a class=\"page\" href=\"".$link."page=".$totalpages."\"><span>Last page</span></a>";
  71. }
  72. }
  73. return $out;
  74. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.