Posted By

Tamedo on 11/23/07


Tagged

paging


Versions (?)

Who likes this?

18 people have marked this snippet as a favorite

jonhenshaw
luman
sbbath
vali29
skywalker
emuman
JimiJay
stavelin
ibomb
digiloper
shii
elgermano
nb109
tapdrup
badcircle
mecha
prit
ringo380


php paging


 / Published in: PHP
 

  1. <html>
  2. <head>
  3. <title>Implementing Paging with next and prev</title>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  5. </head>
  6.  
  7. <body>
  8. <?php
  9. include '../library/config.php';
  10. include '../library/opendb.php';
  11.  
  12. // how many rows to show per page
  13. $rowsPerPage = 20;
  14.  
  15. // by default we show first page
  16. $pageNum = 1;
  17.  
  18. // if $_GET['page'] defined, use it as page number
  19. if(isset($_GET['page']))
  20. {
  21. $pageNum = $_GET['page'];
  22. }
  23.  
  24. // counting the offset
  25. $offset = ($pageNum - 1) * $rowsPerPage;
  26.  
  27. $query = "SELECT val FROM randoms LIMIT $offset, $rowsPerPage";
  28. $result = mysql_query($query) or die('Error, query failed');
  29.  
  30. // print the random numbers
  31. while(list($val) = mysql_fetch_array($result))
  32. {
  33. echo "$val <br>";
  34. }
  35.  
  36. echo '<br>';
  37.  
  38. // how many rows we have in database
  39. $query = "SELECT COUNT(val) AS numrows FROM randoms";
  40. $result = mysql_query($query) or die('Error, query failed');
  41. $row = mysql_fetch_array($result, MYSQL_ASSOC);
  42. $numrows = $row['numrows'];
  43.  
  44. // how many pages we have when using paging?
  45. $maxPage = ceil($numrows/$rowsPerPage);
  46.  
  47. $self = $_SERVER['PHP_SELF'];
  48.  
  49. // creating 'previous' and 'next' link
  50. // plus 'first page' and 'last page' link
  51.  
  52. // print 'previous' link only if we're not
  53. // on page one
  54. if ($pageNum > 1)
  55. {
  56. $page = $pageNum - 1;
  57. $prev = " <a href=\"$self?page=$page\">[Prev]</a> ";
  58.  
  59. $first = " <a href=\"$self?page=1\">[First Page]</a> ";
  60. }
  61. else
  62. {
  63. $prev = ' [Prev] '; // we're on page one, don't enable 'previous' link
  64. $first = ' [First Page] '; // nor 'first page' link
  65. }
  66.  
  67. // print 'next' link only if we're not
  68. // on the last page
  69. if ($pageNum < $maxPage)
  70. {
  71. $page = $pageNum + 1;
  72. $next = " <a href=\"$self?page=$page\">[Next]</a> ";
  73.  
  74. $last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";
  75. }
  76. else
  77. {
  78. $next = ' [Next] '; // we're on the last page, don't enable 'next' link
  79. $last = ' [Last Page] '; // nor 'last page' link
  80. }
  81.  
  82. // print the page navigation link
  83. echo $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
  84.  
  85. include '../library/closedb.php';
  86. ?>
  87. </body>
  88. </html>

Report this snippet  

You need to login to post a comment.