Simple PHP Pagination Class

This is a simple to use PHP pagination class object to make it easier for those not comfortable with paginating results to be able to do so with ease. Simply pass the regular query for all results, the page number, set the number of results per page and you've got a fully working PHP paginator. There are also lots of other features you can achieve including the pagination links can be customised with the templates

<?php

/*******************************************************************************
*                                  Pagination class                            *
*                             Created: 12th January 2009                       *
*                             Updated: 9th September 2009                      *
*                             ©Copyright Jay Gilford 2009                      *
*                              http://www.jaygilford.com                       *
*                            email: jay [at] jaygilford.com                    *
*******************************************************************************/
 
class pagination
{
    ################################
    # PRIVATE VARS - DO NOT ALTER  #
    ################################
    private $_query = '';
    private $_current_page = 1;
    private $_padding = 2;
    private $_results_resource;
    private $_output;
 
    ################################
    #       RESULTS VARS           #
    ################################
    public $results_per_page = 10;          #Number of results to display at a time
    public $total_results = 0;              #Total number of records
    public $total_pages = 0;                #Total number of pages
 
    public $link_prefix = '/?page=';        #String for link to go before the page number
    public $link_suffix = '';               #String for link to go after the page number
    public $page_nums_separator = ' | ';    #String to go between the page number links
 
    ################################
    #      ERROR HOLDING VAR       #
    ################################
    public $error = null;
 
    ################################
    # PAGINATION TEMPLATE DEFAULTS #
    ################################
    public $tpl_first = '<a href="{link}">&laquo;</a> | ';
    public $tpl_last = ' | <a href="{link}">&raquo;</a> ';
 
    public $tpl_prev = '<a href="{link}">&lsaquo;</a> | ';
    public $tpl_next = ' | <a href="{link}">&rsaquo;</a> ';
 
    public $tpl_page_nums = '<span><a href="{link}">{page}</a></span>';
    public $tpl_cur_page_num = '<span>{page}</span>';
 
    /**
     * In the above templates {link} is where the link will be inserted and {page} is
     * where the page numbers will be inserted. Other than that, you can modify them
     * as you please
     *
     * NOTE: You should have a separator of some sort at the right of $tpl_first and
     * $tpl_prev as above in the defaults, and also have a separator of some sort
     * before the $tpl_next and $tpl_last templates
     **/
 
 
    ##################################################################################
 
 
    public function __construct($page, $query)
    {
        #Check page number is a positive integer greater than 0 and assign it to $this->_current_page
        if ((int)$page > 0)
            $this->_current_page = (int)$page;
 
        #Remove any LIMIT clauses in the query string and set if
        $query = trim(preg_replace('/[\s]+LIMIT[\s]+\d+([\s,]*,[^\d]*\d+)?/i', '', $query));
        if (empty($query)) {
            return false;
        } else {
            $this->_query = $query;
        }
    }
 
    /**
     * pagination::paginate()
     *
     * Processes all values and query strings and if successful
     * returns a string of html text for use with pagination bar
     *
     * @return string;
     */
    public function paginate()
    {
        $output = '';
 
        #########################################
        # GET TOTAL NUMBER OF RESULTS AND PAGES #
        #########################################
        $result = mysql_query($this->_query);
        if (!$result) {
            $this->error = __line__ . ' - ' . mysql_error();
            return false;
        }
        $this->total_results = mysql_num_rows($result);
        $this->total_pages = ceil($this->total_results / $this->results_per_page);
 
        ########################
        # FREE RESULT RESOURCE #
        ########################
 
        ################################
        # IF TOTAL PAGES <= 1 RETURN 1 #
        ################################
        if ($this->total_pages <= 1)
        {
        	$this->_results_resource = $result;
			$this->_output = '1';
			return $this->_output;
        }
 
        mysql_free_result($result);
 
        ###################################################
        # CHECK CURRENT PAGE ISN'T GREATER THAN MAX PAGES #
        ###################################################
        if ($this->_current_page > $this->total_pages)
            $this->_current_page = $this->total_pages;
 
        ######################################
        # SET FIRST AND LAST PAGE VALUES AND #
        # ERROR CHECK AGAINST INVALID VALUES #
        ######################################
        $start = ($this->_current_page - $this->_padding > 0) ? $this->_current_page - $this->
            _padding : '1';
        $finish = ($this->_current_page + $this->_padding <= $this->total_pages) ? $this->
            _current_page + $this->_padding : $this->total_pages;
 
        ###########################################
        # CREATE LIMIT CLAUSE AND ASSIGN TO QUERY #
        ###########################################
        $limit = ' LIMIT ' . ($this->results_per_page * ($this->_current_page - 1)) .
            ',' . $this->results_per_page;
        $query = $this->_query . $limit;
 
        #############################################
        # RUN QUERY AND ASSIGN TO $_result_resource #
        #############################################
        $result = mysql_query($query);
        if ($result === false) {
            $this->error = __line__ . ' - ' . mysql_error();
            return false;
        }
        $this->_results_resource = $result;
 
        ###########################################
        # ADD FIRST TO OUTPUT IF CURRENT PAGE > 1 #
        ###########################################
        if ($this->_current_page > 1) {
            $output .= preg_replace('/\{link\}/i', $this->link_prefix . '1' . $this->
                link_suffix, $this->tpl_first);
        }
 
        ##########################################
        # ADD PREV TO OUTPUT IF CURRENT PAGE > 1 #
        ##########################################
        if ($this->_current_page > 1) {
            $output .= preg_replace('/\{link\}/i', $this->link_prefix . ($this->
                _current_page - 1) . $this->link_suffix, $this->tpl_prev);
        }
 
        ################################################
        # GET LIST OF LINKED NUMBERS AND ADD TO OUTPUT #
        ################################################
        $nums = array();
        for ($i = $start; $i <= $finish; $i++) {
            if ($i == $this->_current_page) {
                $nums[] = preg_replace('/\{page\}/i', $i, $this->tpl_cur_page_num);
            } else {
                $patterns = array('/\{link\}/i', '/\{page\}/i');
                $replaces = array($this->link_prefix . $i . $this->link_suffix, $i);
                $nums[] = preg_replace($patterns, $replaces, $this->tpl_page_nums);
            }
        }
        $output .= implode($this->page_nums_separator, $nums);
 
        ##################################################
        # ADD NEXT TO OUTPUT IF CURRENT PAGE < MAX PAGES #
        ##################################################
        if ($this->_current_page < $this->total_pages) {
            $output .= preg_replace('/\{link\}/i', $this->link_prefix . ($this->
                _current_page + 1) . $this->link_suffix, $this->tpl_next);
        }
 
        ############################################
        # ADD LAST TO OUTPUT IF FINISH < MAX PAGES #
        ############################################
        if ($this->_current_page < $finish) {
            $output .= preg_replace('/\{link\}/i', $this->link_prefix . $this->total_pages, $this->
                tpl_last);
        }
 
        $this->_output = $output;
        return $output;
    }
 
 
    /**
     * pagination::padding()
     *
     * Sets the padding for the pagination string
     *
     * @param int $val
     * @return bool
     */
    public function padding($val)
    {
        if ((int)$val < 1)
            return false;
 
        $this->_padding = (int)$val;
        return true;
    }
 
 
    /**
     * pagination::resource()
     *
     * Returns the resource of the results query
     *
     * @return resource
     */
    function resource()
    {
        return $this->_results_resource;
    }
 
 
    /**
     * pagination::__tostring()
     * returns the last pagination output
     *
     * @return string
     */
    function __tostring()
    {
        if (trim($this->_output)) {
            return trim($this->_output);
        }else{
        	return '';
        }
    }
}

Usage

Class Homepage: http://www.jaygilford.com/php/completely-customisable-php-pagination-class/

To instantiate the class you will need two things
- The current page number (from $_GET['page'] for example)
- The query you need to run

So say we have
$query = "SELECT * FROM PRODUCTS";
$page = isset($_GET['page']) ? $_GET['page'] : 1;

we would then call the class with
$pag = new pagination($page, $query);

Once that has been done, all that is left is to call
$pag->paginate();

This will run the pagination, and store the MySQL result for your results loop.
To get the resource, simply use
$pag->resource();
for example, suppose your normal code was
while($row = mysql_fetch_assoc($result)) {
// Code here for each result
}
Simply change $result to $pag->resource() and it will get the results from the query

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

You can also change a number of settings for the class, such as putting
$pag->results_per_page = 5;
will change the number of results to 5 per page


PLEASE BE SURE TO CHANGE ALL SETTINGS BETWEEN CREATING THE CLASS AND THE $pag->paginate(); OR THE CHANGE WONT BE SEEN IN THE RESULTS

Finally, to show your pagination links output, simply use
echo $pag;
This will show the | >>| structure wherever you echo it. You can change the format of these using $pag->tpl_prev for example to change the previous page output link

If you have any questions regarding this feel free to contact me via email (contact details can be found at http://www.jaygilford.com/contact/)


Comments

guest
Posted on 08.03.2011 11:45

Thank you verry much for this info, it helped me allot, thanks again.

guest
Posted on 09.03.2010 08:44

nice script

guest
Posted on 10.02.2010 06:09

vijay: This pagination topic is very help to me

Add your comment