Posted By

davidsword on 10/11/08


Tagged

mysql database php page pagination


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

luman
bryandease
vali29


Pagination


 / Published in: PHP
 

URL: http://davidsword.ca/

Displays mysql entries by pages

  1. <?php
  2. //# of posts to display per page
  3. $display = 5;
  4.  
  5. //adds your page (if any) between like so '?{$uri}page=#'
  6. $uri = "p=blog&";
  7.  
  8. //Get current page
  9. $page = (!empty($_GET['page'])) ? $_GET['page'] : '0';
  10.  
  11. //Find post to start on, depending on page
  12. $start = ($page == 0) ? $start = 0 : $start = (($page-1)*$display);
  13.  
  14. //Print content & count number printed
  15. $query = "SELECT * FROM table LIMIT {$start},{$display}";
  16. $result = mysql_query($query) or die(mysql_error());
  17. $displayed = 0;
  18. while($row = mysql_fetch_array($result)) {
  19. echo $row['content']."<br />";
  20. $displayed++;
  21. }
  22.  
  23. //Get number of total posts
  24. $count = mysql_query("SELECT id FROM table");
  25. $rows = mysql_num_rows($count);
  26.  
  27. //Get number of total pages
  28. $pages = ceil($rows/$display);
  29.  
  30. //Make next/prev links
  31. $next = $page+1;
  32. $prev = $page-1;
  33.  
  34. //Unlink if next/prev doesn't exsist
  35. $prevpage = ($prev == 0 || $prev == -1) ?
  36. "&lt;&lt; Prev" : "<a href='?{$uri}page={$prev}'>&lt;&lt; Prev</a>";
  37. $nextpage = ($next < $pages+1) ?
  38. "<a href='?{$uri}page={$next}'>Next &gt;&gt;</a>" : "Next &gt;&gt;";
  39.  
  40. //Get showing from-to numbers
  41. $from = $start;
  42. $from = ($from == 0) ? 1 : $from+1;
  43. $to = $start+$displayed;
  44.  
  45. //Print stats
  46. $page_num = ($page == 0) ? '1': $page;
  47. echo "Showing entries {$from}-{$to}/{$rows},
  48. on page {$page_num}/{$pages} <br /><br />";
  49.  
  50. //Print individual page number links
  51. echo "{$prevpage} &nbsp; [";
  52. $i = 1;
  53. while($i != $pages+1) {
  54. //Print pages & add coma to all but last page #
  55. echo "<a href='?{$uri}page={$i}'>{$i}</a>";
  56. if($i != $pages) {echo ", ";}
  57. $i = $i+1;
  58. }
  59. echo "] &nbsp; {$nextpage}";
  60. ?>

Report this snippet  

You need to login to post a comment.