Pagination of Data using PHP-MySQL


Pagination of Data (Paging) using PHP (Hyper Text Pre Processor) and MySQL (the great database)

 

Note: I wrote this post first on October , 2007 , nearly 3 years back and since then this post got a lot of audiences. Surely this topic is one of the good ones for the newbies. After reading the responses for this post I saw that users are facing some errors and after a long while I got some time to have a second look. So I have again installed PHP, APACHE, MYSQL and MYSQL WorkBench in my local machine and tested the script like a user. I have found some new bugs and made the modifications accordingly. Now the Script is completely new and tested fully.

To simplify I tried to use some out of box functionality so that one can run the example right away.

For the sample database I have used “SAKILA” database from MySQL. I have only used the “Customer” table for the example, but this can be extended to a bigger example. Hope you’ll find this useful.


First: Install the SAKILA Database to your local MySQL instance. You can download it from here. We will be using the CUSTOMER table. Here is the table for your reference:


CREATE TABLE customer (

customer_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,

store_id TINYINT UNSIGNED NOT NULL,

first_name VARCHAR(45) NOT NULL,

last_name VARCHAR(45) NOT NULL,

email VARCHAR(50) DEFAULT NULL,

address_id SMALLINT UNSIGNED NOT NULL,

active BOOLEAN NOT NULL DEFAULT TRUE,

create_date DATETIME NOT NULL,

last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

PRIMARY KEY (customer_id),

KEY idx_fk_store_id (store_id),

KEY idx_fk_address_id (address_id),

KEY idx_last_name (last_name),

CONSTRAINT fk_customer_address FOREIGN KEY (address_id) REFERENCES address (address_id) ON DELETE RESTRICT ON UPDATE CASCADE,

CONSTRAINT fk_customer_store FOREIGN KEY (store_id) REFERENCES store (store_id) ON DELETE RESTRICT ON UPDATE CASCADE

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Second: This table already have a lot of data. You can verify it by the simple select command.

Initially it has nearly 599 rows. A very good amount of data to test our code.

Third: Create and Test this script

Create a file named pagination.php and put the below contents to that file. Upload that file to your local server or main server.

I have uploaded that on my local server where php is running. If you are testing this script elsewhere then change http://localhost with your server host name.

You’ll see that I have used a variable called $page_name to hold the page name with full address. This is because the link to the page is being used multiple times inside the coding. So, only one place to change your page name, rest will be taken care of automatically.


<?php
//Global Variable:
 

$page_name = “http://localhost/pagination.php&#8221;;

//REMEMBER TO CONNECT TO DATABASE!

$link = mysql_connect(‘localhost’,’root’,’rootpassword’)

or die(“Error connecting to Database: ” . mysql_error());

mysql_select_db(‘sakila’) or

die(“Error Selecting Database: ” . mysql_error());

//**EDIT TO YOUR TABLE NAME, ETC.

$t = mysql_query(“SELECT count(*) as cnt FROM customer”);

if(!$t){

die(“Error quering the Database: ” . mysql_error());

}

$a = mysql_fetch_object($t);

$total_items = $a->cnt;

echo “Total Number of records in Database: “.$total_items;

echo “<br/>”;

$limit= (isset($_GET[“limit”])) ? $_GET[“limit”] : 10;

$page= (isset($_GET[“page”]))? $_GET[“page”] : 1;

echo “This is Page Number: ” . $page . “<br/>”;

echo “Current Limit: “. $limit. “<br/>”;

//Set defaults if: $limit is empty, non numerical,

//less than 10, greater than 50

if((!$limit) || (is_numeric($limit) == false)

|| ($limit < 10) || ($limit > 50)) {

$limit = 10; //default

}

//Set defaults if: $page is empty, non numerical,

//less than zero, greater than total available

if((!$page) || (is_numeric($page) == false)

|| ($page < 0) || ($page > $total_items)) {

$page = 1; //default

}

//calculate total pages

$total_pages = ceil($total_items / $limit);

$set_limit = ($page * $limit) – $limit;

echo “Total Pages: $total_pages <br/>”;

//query: **EDIT TO YOUR TABLE NAME, ETC.

$q = mysql_query(“SELECT * FROM customer LIMIT $set_limit, $limit“);

if(!$q) die(mysql_error());

$no_row = mysql_num_rows($q);

if($no_row == 0) die(“No matches met your criteria.”);

//Results per page:

echo(“<br/>Records Per Page:

<a href=$page_name?limit=10&page=1>

10</a> |

<a href=$page_name?limit=25&page=1>

25</a> |

<a href=$page_name?limit=50&page=1>

50</a><br/>

“);

//show data matching query:

while($object = mysql_fetch_object($q)) {

//print your data here.

echo(“<br/>————————————–<br/>”);

echo(“First Name: “.$object->first_name.”<BR/>”);

echo(“Last Name: “.$object->last_name.”<BR/>”);

echo(“Email: “.$object->email.”<BR/>”);

echo(“————————————–<br/>”);

}

//Results Per Page: Same as earlier one

echo(“<br/>Records Per Page:

<a href=$page_name?limit=10&page=1>

10</a> |

<a href=$page_name?limit=25&page=1>

25</a> |

<a href=$page_name?limit=50&page=1>

50</a><br/>

“);

//prev. page

$prev_page = $page – 1;

if($prev_page >= 1) {

echo(“<b><<</b> <a href=$page_name?limit=$limit&page=$prev_page>

<b>Prev.</b></a>”);

}

//Display middle pages:

for($a = 1; $a <= $total_pages; $a++)

{

if($a == $page) {

echo(“<b> $a</b> | “); //no link

}

else {

echo(”

<a href=$page_name?limit=$limit&page=$a> $a

</a> | “);

}

}

//Next page:

$next_page = $page + 1;

if($next_page <= $total_pages) {

echo(”

<a href=$page_name?limit=$limit

&page=$next_page><b>Next</b></a> > >”);

}
//all done
?>

Four: Run this script in browser and see pagination with php and mysql in action.

Explanation: First this script will query the database and get total number of rows by the “SELECT count(*) as cnt FROM customer ” query. It will return the count as cnt. Now get the count and store it in the variable $total_items.

Now get the limit and page number from the GET variables. For the first time both will be null, so by default we will set the limit to 10 and page to 1.

If this variables are not blank, i.e. if the users click on the next or previous or page links then the page number and number of items to displayed will be not null and we will display data accordingly.

If some how this limit and page values are greater than the specified values or less than the specified values we will set them as default.

Now we will calculate how many pages the data will span. i.e. if we select 10 data to displayed at one time and total number of data are 85 then there will be 9 pages and by default the first page will be displayed. In this way if we choose to display 25 data at one time then the total number of pages will be 4, first 3 will display 25 data each and the last will display 10 data.

Hope this tutorial will help you to explore the vast world of pagination using php and mysql.

Kindly send me any queries that you might have.

 

Here is the code to download. Its currently in a Word Document.