Special Offer - Get $90 Discount and Host Your Dream Web Site @ Dreamhost for 1 Year Click Here. Promo Code SLJ345
Back To Top
WordPress Web Application Development
Develop Powerfull Web Applications Using Cutting Edge WordPress Development Techniques

Creating a PHP Pagination Library From Scratch

on 2011/08/21 11:54 PM stored in: Uncategorized and tagged:

Introduction To PHP Pagination

What is Pagination ?
Pagination is where we broke the number of results for a list into small parts called pages.

 

Why We Use Pagination
Without pagination we will have to get all the resullts and display in a single page . It takes lot of load time and also page scroll gets very
long.

Creating the Pagination Library from Scratch

Before you digg into this tutorial you might want to see a demo to find out exactly what we are going to talk about. Click the link below to watch the demo.

Pagination Demo

Creating the Pagination Library from Scratch

Lets start by writing the pagination class.

class Pagination {
    public $recordsPerPage;  // Number of Items to be displayed in a Single Page
    public $totalRecords;   // Total number of items returned from the sql query
    public $firstLink;
    public $lastLink;
    public $pages;        // Number of pages from the query - $totalRecords / $recordsPerPage
    public $previous;     // Number of the previous page
    public $next;         // Number of the next page
    public $currentPage;  // Number of the current page
    public $numLinks;  // Number of pages to display after and before current page
    public $paginateStart;   // Starting value of the list
    public $paginationBar;  // Html string generated for pagination
}

 

Then we have to initialize the variables and do the calculations before preparing the Pagination Links. I have done this inside the generateLinks method in the Pagination class.

 

public function generateLinks($totalRecords, $recordsPerPage, $numLinks, $current=1) {
		if ($totalRecords > 0) {
			$this->pages = ceil($totalRecords / $recordsPerPage);
		} else {
			$this->pages = 0;
		}
		$this->currentPage = $current;
		$this->previous = $current - 1;
		$this->next = $current + 1;
		$this->numLinks = $numLinks;
		$this->recordsPerPage = $recordsPerPage;
		$this->paginateStart = ($this->currentPage - 1) * $this->recordsPerPage;
}
  • We have to pass the values for number of records returned from sql query , records per page , number of pages before and after current page and current page number to the generateLinks function.
  • Then if the number of records is greater than 0 we calculate the number of pages using $totalRecords / $recordsPerPage and getting the ceil value.
  • If Number of records is 0 we dont have any pages or pagination links.

 

Once we initialize variables properly we can generate the links for the pagination buttons using following methods.

 

                                    
		        $str = "<div class='paginateMain'>";
		        $str .= $this->generatePreviousLink();
		        $str .= $this->generateBackwardLinks();
		        $str .= $this->generateCurrentPage();
		        $str .= $this->generateForwardLinks();
		        $str.= $this->generateNextLink();
		        $str .= '</div>';
		        $this->paginationBar = $str;
  • Above code will generate the necessary html code for the pagination links.
  • Seperate methods are used to generate links for each functionality.
  • Ex: generatePreviousLink() method will generate the link for the previos page.

 

All the functions mentioned in the previos section works in same structure. So i am going to explain functionality of generatePreviousLink function.

 

private function generatePreviousLink() {
		if ($this->pages > 0) {
			if( ($this->currentPage - 1) >= 1 ) {
				$previousLink = "<div class='paginationNum' onclick=loadPaginate('$this->previous')>Previous </div>";
				return $previousLink;
			}else {
				return '';
			}
		}else {
			return '';
		}
	}
  • First we check if number of pages greater than 0.
  • Then we check if the current page is the first page of the list. If so we dont have to create a previos link. Otherwise we create the link for the previos button.

How to use the library

      if(isset ($_GET['page'])) {
			loadpaginate($_GET['page']);
		}else {
			loadpaginate();
		}

		function loadpaginate($page=1) {
			$result=mysql_query("select description from title");
			$numrow=mysql_num_rows($result);

			$paginater =  new Pagination();
			$paginater->generateLinks($numrow, 4, 2,$page);
			$searchResult = generateSearchResults($paginater->paginateStart ,  $paginater->recordsPerPage);


			$out= "<div id='content'>";
			$out.= "<div class='recordsTitle'>Users</div>";
			while ($row = mysql_fetch_array($searchResult)) {
				$out.= "<div class='records'>".$row['description']."</div>";
			}

			$out.= $paginater->paginationBar;

			
			$out.= "</div>";
			echo $out;

		}

		function generateSearchResults($limit=0, $offset=10) {


			$searchResult = array();

			$sql = "select description from title limit $limit,$offset";
			$res1 = mysql_query($sql);
			return $res1;
		}

Complete Source Code

We can create a simple pagination library to use in your projects using the above code. Complete code for this article is provided in the Source Code section. Enjoy using it in your projects and feel free to comment on advantages , disadvantages and suggestions and any difficulties in using this library in different frameworks.

class Pagination {
	public $recordsPerPage;
	public $totalRecords;
	public $firstLink;
	public $lastLink;
	public $pages;
	public $previous;
	public $next;
	public $currentPage;
	public $numLinks;
	public $paginateStart;
	public $paginationBar;

	public function generateLinks($totalRecords,$recordsPerPage,$numLinks,$current=1){

		if ($totalRecords > 0) {
			$this->pages = ceil($totalRecords / $recordsPerPage);
		} else {
			$this->pages = 0;
		}

		$this->currentPage = $current;
		$this->previous = $current - 1;
		$this->next = $current + 1;
		$this->numLinks = $numLinks;
		$this->recordsPerPage = $recordsPerPage;
		$this->paginateStart = ($this->currentPage - 1) * $this->recordsPerPage;

		$str = "<div class='paginateMain'>";
		//$str .= $this->generateFirstLink();
		$str .= $this->generatePreviousLink();

		$str .= $this->generateBackwardLinks();
		$str .= $this->generateCurrentPage();
		$str .= $this->generateForwardLinks();

		$str.= $this->generateNextLink();
		//$str .= $this->generateLastLink();
		$str .= '</div>';
		$this->paginationBar = $str;
	}

	

	private function generateNextLink() {
		if ($this->pages > 0) {
			if( ($this->pages - $this->currentPage) >= 1 ) {
				$nextLink = "<div class='paginationNum'
									onclick=loadPaginate('$this->next')>Next</div>";
				return $nextLink;
			}else {
				return '';
			}
		}else {
			return '';
		}
	}

	private function generatePreviousLink() {
		if ($this->pages > 0) {
			if( ($this->currentPage - 1) >= 1 ) {
				$previousLink = "<div class='paginationNum'
									onclick=loadPaginate('$this->previous')>Previous</div>";
				return $previousLink;
			}else {
				return '';
			}
		}else {
			return '';
		}
	}

	private function generateFirstLink() {
		if ($this->pages > 0) {
			if( ($this->currentPage) > 1 ) {
				$previousLink = "<div class='paginationNum'
									onclick=loadPaginate('1')>First</div>";
				return $previousLink;
			}else {
				return '';
			}
		}else {
			return '';
		}
	}

	private function generateLastLink() {
		if ($this->pages > 0) {
			if( ($this->currentPage) != $this->pages ) {
				$previousLink = "<div class='paginationNum'
									onclick=loadPaginate('$this->pages')>Last</div>";
				return $previousLink;
			}else {
				return '';
			}
		}else {
			return '';
		}
	}

	private function generateCurrentPage() {
		return "<div class='paginationNumCurrent'
						onclick=loadPaginate('$this->currentPage')>$this->currentPage</div>";
	}

	private function generateForwardLinks() {
		if ($this->pages > 0) {
			$forwardLink = '';

			$forwardLinkLength = ($this->currentPage+$this->numLinks > $this->pages)? $this->pages :
											($this->numLinks+$this->currentPage);

			for ($i = ($this->currentPage+1); $i <= ($forwardLinkLength); $i++) {
				$forwardLink.= "<div class='paginationNum'
									onclick=loadPaginate('$i')>$i</div>";
			}
			return $forwardLink;
		}else {
			return '';
		}
	}

	private function generateBackwardLinks() {
		if ($this->pages > 0) {
			$backLink = '';

			$backLinkLength = ($this->currentPage-$this->numLinks < 1)? '1' :
											($this->currentPage-$this->numLinks);

			for ($i = ($backLinkLength); $i <= ($this->currentPage-1); $i++) {
				$backLink.= "<div class='paginationNum' onclick=loadPaginate('$i')>$i</div>";
			}
			return $backLink;
		}else {
			return '';
		}
	}

}


3 Responses to “Creating a PHP Pagination Library From Scratch”

  1. Rickie Bliler Says:

    Very good blog, thank you so much for your effort in writing the posts.

  2. admin Says:

    Thanks for your comments

  3. Elliptical machine reviews Says:

    Very nice, i suggest webmaster can set up a forum, so that we can talk and communicate.

Leave a Reply

Follow Us On Facebook