Home About Portfolio Links Contact

Pagination with PHP and MySQL

In this tutorial I will show you how to take a list of states from a database and break up the states into groups of 10 per page.

Pagination Demo

 

| More
Share with friends and family

 

Create Database

First we need to create a database that we can extract our data from. I put up a short script you can copy from my google docs, paste it into a php file and run it to create the database table and fields.

For a copy of the database script Click Here...

 

Open Connection to your Database.

Since we are collecting our data from the database we need to open a connection.

  1. <?php
  2. // OPEN DATABASE
  3. define("HOSTNAME","localhost");
  4. define("USERNAME"," *** USERNAME HERE *** ");
  5. define("PASSWORD"," *** PASSWORD HERE *** ");
  6. define("DATABASE"," *** DATABASE HERE *** ");
  7.  
  8. mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die("Connetion to database failed!");
  9. mysql_select_db(DATABASE);
  10. ?>

 

Pagination Script

In this script we are going to determine how much data we want to display per page.

  1. <?php
  2. // ROWS DISPLAYED PER PAGE
  3. $rows_per_page = 10;
  4.  
  5. // GET PAGE NUMBER
  6. $page = $_GET['page'];
  7. $offset = (!empty($page)) ? $page : $page = 1;
  8.  
  9. // URL CLEAN UP
  10. $self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
  11. $self = str_replace("page={$offset}", "", $self);
  12.  
  13. // GET LIST OF STATES
  14. $offset = ($page) ? ($page - 1) * $rows_per_page : 0;
  15. $query = "SELECT * ".
  16. "FROM states_list ".
  17. "ORDER BY id ".
  18. "LIMIT {$offset},{$rows_per_page}";
  19. $result = mysql_query($query);
  20.  
  21. // GET NUMBER OF PAGES
  22. $ltq = mysql_query("SELECT * FROM states_list");
  23. $listings_total = mysql_num_rows($ltq);
  24. $NumPgs = ceil($listings_total / $rows_per_page);
  25. ?>
  26.  
  27. <div style="width: 500px; margin:auto; border:1px #666666 solid;">
  28. <div style="background:#CCCCCC; text-align:center; padding:4px; border-bottom:1px #666666 solid;"><strong>LIST OF STATES</strong></div>
  29. <?php while($row = mysql_fetch_array($result)){ ?>
  30. <div style="text-align:center; padding:4px; border-bottom:1px #666666 solid;"><?=$row['states']?></div>
  31. <?php } ?>
  32. <span style="float:right">
  33. <?=$prev = ($NumPgs > 0 && $page!=1) ? "<a href=\"{$self}page=".($page-1)."\">&lt;&lt;Prev</a>&nbsp;&nbsp;":
  34. "&lt;&lt;Prev&nbsp;&nbsp;"; ?>
  35. [Page <?php echo $page; ?>]
  36. <?=$next = ($page < $NumPgs) ? "<a href=\"{$self}page=".($page+1)."\">&nbsp;&nbsp;Next&gt;&gt;</a>":
  37. "&nbsp;&nbsp;Next&gt;&gt;";?>&nbsp;
  38. </span>
  39. <b>&nbsp;<?=$offset+1?> to <?=$offset+$rows_per_page?>, of <?=$listings_total?> States</b>
  40. </div>
  41. ?>

 

 

Explanation

Rows Displayed Per Page / Line 3:

    $rows_per_page = 10;	

On line 3 of our pagination script we want to set the number of data we want to display per page. I put this at the top so it's easy to find for later pagination template use.

Get Page Number / Lines 6-7:

   $page = $_GET['page'];
   $offset = (!empty($page)) ? $page : $page = 1;

Since we are using URL parameters to get our page number, we need to to check the URL and see if our page param is empty or not. So, for example, if the URL to our pagination page is http://www.hollen-b.com/tutorial/pagination_demo.php we will default to page 1. If the URL to our pagination page is http://www.hollen-b.com/tutorial/pagination_demo.php?page=2 we go to page 2.

URL Clean Up / Lines 10-11:

   $self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
   $self = str_replace("page={$offset}", "", $self);

Without this every time someone clicks a prev or next link our parameters will start to stack up in our URL. So we need to get the URL and remove the old page parameter.

Get List Of States / Lines 14-18:

   $offset = ($page) ? ($page - 1) * $rows_per_page : 0;
   $query = "SELECT * ".
            "FROM states_list ".
            "ORDER BY id ".
            "LIMIT {$offset},{$rows_per_page}";
   $result = mysql_query($query);

Every time we load the page we are going to run two arguments to MySQL using LIMIT X, Y. X is the starting point, and Y is the total amount of records we want to display. To get X in our case is $offset, we need to first get the page number were on. Subtract the page number by 1, multiply that number by the total rows per page and we now should have the X value we need. Y is simply our number of rows we want to display which was set on line 3.

Get Number Of Pages / Line 22-24:

   $ltq  = mysql_query("SELECT * FROM states_list");
   $listings_total = mysql_num_rows($ltq);
   $NumPgs = ceil($listings_total / $rows_per_page);

If we query the database for our total number of rows, we can divide that by the total rows per page, which should give us our total number of pages. By using ceil function we can round our total number of pages to the next highest integer.

 

 

| More
Comments
LaurenSumited: 10/22/2009
This was SO useful today for my job, thanks for posting this tutorial!
RobSumited: 10/20/2009
Thnx for the code i think ill play around with this one a little bit.
Add Comment