Showing posts with label PHP Pagination. Show all posts
Showing posts with label PHP Pagination. Show all posts

Monday, 20 July 2015

PHP: Simple Pagination Using PHP MySQL

Webpage with more number of rowed data will make the page lengthier, pagination makes the long rows into small number of rows and remaining in next pages. Pagination in a webpage will make the webpage structure more crispy. Here is the tutorial about how to make simple pagination using php mysql

<html>
<style type="text/css">

#content
{
width: 900px;
margin: 0 auto;
font-family:Arial, Helvetica, sans-serif;
}
.page
{
float: right;
margin: 0;
padding: 0;
}
.page li
{
list-style: none;
display:inline-block;
}
.page li a, .current
{
display: block;
padding: 5px;
text-decoration: none;
color: #8A8A8A;
}
.current
{
font-weight:bold;
color: #000;
}
.button
{
padding: 5px 15px;
text-decoration: none;
background: #333;
color: #F3F3F3;
font-size: 13PX;
border-radius: 2PX;
margin: 0 4PX;
display: block;
float: left;
}
</style>
<body>
<div id="content">
<?php
$query1=mysql_connect("localhost","root","");
mysql_select_db("freeze_demo",$query1);

$start=0;
$limit=10;

if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}

$query=mysql_query("select * from pagination LIMIT $start, $limit");
echo "<ul>";
while($query2=mysql_fetch_array($query))
{
echo "<li>".$query2['text1']."</li>";
}
echo "</ul>";
$rows=mysql_num_rows(mysql_query("select * from pagination"));
$total=ceil($rows/$limit);

if($id>1)
{
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
}
if($id!=$total)
{
echo "<a href='?id=".($id+1)."' class='button'>NEXT</a>";
}

echo "<ul class='page'>";
for($i=1;$i<=$total;$i++)
{
if($i==$id) { echo "<li class='current'>".$i."</li>"; }

else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; }
}
echo "</ul>";
?>
</div>
</body>
</html>



 

Wednesday, 3 June 2015

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                      *
*                                                                              *
*                                                                              *
*                                                                              *
*******************************************************************************/
 
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
 

Tuesday, 2 June 2015

PHP pagination class

<?php
class pagination
{
 public function __construct()
 {
 }
 public function calculate_pages($total_rows, $rows_per_page, $page_num)
 {
  $arr = array();
  // calculate last page
  $last_page = ceil($total_rows / $rows_per_page);
  // make sure we are within limits
  $page_num = (int) $page_num;
  if ($page_num < 1)
  {
     $page_num = 1;
  } 
  elseif ($page_num > $last_page)
  {
     $page_num = $last_page;
  }
  $upto = ($page_num - 1) * $rows_per_page;
  $arr['limit'] = 'LIMIT '.$upto.',' .$rows_per_page;
  $arr['current'] = $page_num;
  if ($page_num == 1)
   $arr['previous'] = $page_num;
  else
   $arr['previous'] = $page_num - 1;
  if ($page_num == $last_page)
   $arr['next'] = $last_page;
  else
   $arr['next'] = $page_num + 1;
  $arr['last'] = $last_page;
  $arr['info'] = 'Page ('.$page_num.' of '.$last_page.')';
  $arr['pages'] = $this->get_surrounding_pages($page_num, $last_page, $arr['next']);
  return $arr;
 }
 function get_surrounding_pages($page_num, $last_page, $next)
 {
  $arr = array();
  $show = 5; // how many boxes
  // at first
  if ($page_num == 1)
  {
   // case of 1 page only
   if ($next == $page_num) return array(1);
   for ($i = 0; $i < $show; $i++)
   {
    if ($i == $last_page) break;
    array_push($arr, $i + 1);
   }
   return $arr;
  }
  // at last
  if ($page_num == $last_page)
  {
   $start = $last_page - $show;
   if ($start < 1) $start = 0;
   for ($i = $start; $i < $last_page; $i++)
   {
    array_push($arr, $i + 1);
   }
   return $arr;
  }
  // at middle
  $start = $page_num - $show;
  if ($start < 1) $start = 0;
  for ($i = $start; $i < $page_num; $i++)
  {
   array_push($arr, $i + 1);
  }
  for ($i = ($page_num + 1); $i < ($page_num + $show); $i++)
  {
   if ($i == ($last_page + 1)) break;
   array_push($arr, $i);
  }
  return $arr;
 }
}
?>
 
 

Usage

Simple and raw. No theory, plain code. This is it, PHP pagination class, one of the most wanted snippets for web applications.
How to use it:

Instantiate the class (PHP5 version):

$p = new pagination();

Run the first query to select the number of total rows and call the first function,
with arguments the total rows number, how many rows to show per page and current page number:


$arr = $p->calculate_pages(70, 10, 1);

This function will call the second one in the class to get the surrounding pages of the page 
we are requesting.
The returned result should look like this:
Array
(
[limit] => LIMIT 0,10
[current] => 1
[previous] => 1
[next] => 2
[last] => 7
[info] => Page (1 of 7)
[pages] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
)

 
 
// at middle
$start = $page_num - ceil($show / 2);
$end = $page_num + floor($show / 2 );
if ($end >= $last_page) $start = $last_page - $show;
if ($start < 0) { $start = 0; $end = $show; }
for ($i = $start; $i < $end; $i++)
{
if ($i == $last_page) break;
array_push($arr, $i + 1);
}
return $arr;
 
*****************************************(OR)*****************************
// at middle
$start = $page_num - $show / 2;
if ($start < 1) $start = 0;
if ($last_page- $page_num == 1){
$arr[] = array("p"=> floor($start));
}
for ($i = $start; $i < $page_num; $i++) {
$arr[] = array("p"=>floor($i + 1));
}

for ($i = ($page_num + 1); $i < ($page_num + $show / 2 + 1); $i++) {
if ($i == ($last_page + 1)) break;
$arr[] = array("p"=>floor($i));
}

$a = array();
$i = 0;
foreach ($arr as $page){
if ($i++ < $show) $a[] = $page;
}
 
-------------------------------------------------------------------------------------------------------------------------------------
I tested it using this code below but I got this 

ERROR: "Fatal error: Cannot pass parameter 3 by reference on line $arr = $p->calculate_pages( $result, 10, 1 );"

How to resolve this? ;)

<?php
require_once( 'classes/connection.php' );
require_once( 'classes/php-pagination-class.php' );
$p = new pagination();
$qry = mysql_query( "SELECT * FROM items" ); 
$result = mysql_num_rows( $qry );
$arr = $p->calculate_pages( $result, 10, 1 );
echo "";
echo print_r( $arr );
echo "";
?>