article

Saturday, August 31, 2013

Pagenation using PHP Class

Pagenation using PHP Class

Crate Database table
CREATE TABLE `countries` (
  `ID` smallint(5) unsigned NOT NULL auto_increment,
  `Country` varchar(255) NOT NULL,
  `CountryAbbrev` varchar(10) default NULL,
  `CurrencyAbbr` varchar(4) default NULL,
  `CurrencyRate` float default NULL,
  `CurrencyCode` varchar(3) default NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=289 DEFAULT CHARSET=latin1;

Download table countries
index.php
<?php
    require_once('Pagination.class.php');
    $row_per_page = 20;
    $pagination = new CompletePagination($row_per_page);
    
    $link = mysql_connect('localhost', 'root', '');
    mysql_selectdb('test');
    
    $where = "";
    
    if(isset($_POST['txt_name']))
        $where = " WHERE Country LIKE '%{$_POST['txt_name']}%'";
    else if(isset($_GET['txt_name']) && isset($_GET['page_no']))
        $where = " WHERE Country LIKE '%{$_GET['txt_name']}%'";

    $query_count = "SELECT COUNT(Country) AS tot_rec FROM countries ".$where;
    $result_count = mysql_query($query_count);
    $record_count = mysql_fetch_array($result_count);
    $total_rec = $record_count['tot_rec'];
    
    $pagination->total_rows = $total_rec;    
    $pagination->show_dropdown = true;
    $pagination->show_total_records = true;
    $pagination->show_page_no = true;
    $pagination->show_ellipsis = 20;   //Show Ellipsis if total Pages are greater than or eqaul to 100
    $pagination_html = $pagination->showCompletePagination();

    $pagination->show_ellipsis = 10;
    $pagination->show_dropdown = false;
    $pagination->show_total_records = false;
    $pagination->show_page_no = false;
    $pagination_html2 = $pagination->showCompletePagination();
    
    $query = "SELECT Country, CountryAbbrev, CurrencyAbbr FROM countries ".$where." LIMIT ".$pagination->getLimit() . ", " . $row_per_page;
    $result = mysql_query($query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Pagination</title>
        <link rel="stylesheet" type="text/css" href="completepagination.css" />
    </head>
    <body>
        <div align="center">
        <?php echo $pagination_html; ?>
        <form method="post" action="">
            Country Name: <input type="text" name="txt_name" value="<?php echo @$_REQUEST['txt_name'];?>" />
            <input type="submit" value="Submit" />            
        </form>
        <table border="1" cellpadding="2" cellspacing="2">
            <thead>
            <tr>
                <th>Country</th>
                <th>Country Abb</th>
                <th>Currency Abb</th>
            </tr>
            </thead>
            <tbody>
                <?php
                    while($record = mysql_fetch_array($result)){
                ?>
                <tr>
                    <td><?php echo $record['Country'];?></td>
                    <td><?php echo $record['CountryAbbrev'];?></td>
                    <td><?php echo $record['CurrencyAbbr'];?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php echo $pagination_html2;?>
        </div>
    </body>
</html>
Pagination.class.php
<?php
class CompletePagination 
{
    private $rows_per_page;
    private $url;
    private $page_no;
    
    public $total_rows;
    public $show_dropdown;
    public $show_total_records;
    public $show_page_no;
    public $show_ellipsis = 9;     //Show ... if total pages are more than 10

    /**
     *
     * @param int $rperpage - show the record per page
     * @param int $totrows - total records
     */
    public function __construct($rperpage, $totrows = "") 
    {
        $this->rows_per_page = $rperpage;
        $this->total_rows = $totrows;
        $this->setPageNumber();
        $this->generateCompleteURL();
    }

    /**
     * function sets the pageNumber
     */
    private function setPageNumber() 
    {
        if($_POST)
            $this->page_no = 1;
        else
        {
            if (!isset($_REQUEST['page_no']) && @$_REQUEST['page_no'] == "")
                $this->page_no = 1;
            else
                $this->page_no = $_REQUEST['page_no'];
        }
    }

    /**
     * function gets the limit of pagination
     * @return int 
     */
    public function getLimit() 
    {
        return ($this->page_no - 1) * $this->rows_per_page;
    }

    /**
     * This function generates the complete URL along with the query string
     */
    private function generateCompleteURL() 
    {
        $page_query = (count($_REQUEST) == 0 ? "page_no=" : "&page_no=");

        if (isset($_REQUEST['page_no']))
            unset($_REQUEST['page_no']);

        $this->url = $_SERVER['PHP_SELF'] . "?" . http_build_query($_REQUEST) . $page_query;
    }

    /**
     * function returns the last page, that is generates as the result of Pagination
     * @return int 
     */
    private function getLastPage() 
    {
        return ceil($this->total_rows / $this->rows_per_page);
    }

    /**
     * function generates the DropDown for Pagination
     * @return string 
     */
    private function generateDropdown() 
    {
        if ($this->total_rows == 0)
            return "";

        $str = "";
        $str .= '<select name="drp_page_no" id="drp_page_no" onchange="document.location.href = this.value;">';
        for ($cnt = 1; $cnt <= $this->getLastPage(); $cnt++) 
        {
            if (isset($this->page_no) && $this->page_no == $cnt)
                $str .= '<option value="' . $this->url . $cnt . '" selected="selected">' . $cnt . '</option>';
            else
                $str .= '<option value="' . $this->url . $cnt . '">' . $cnt . '</option>';
        }
        $str .= '</select>';
        return $str;
    }

    /**
     * function generates the complete pagination
     * @return string 
     */
    public function showCompletePagination() 
    {
        $pagination = "";
        $lpm1 = $this->getLastPage() - 1;
        $page = $this->page_no;
        $prev = $this->page_no - 1;
        $next = $this->page_no + 1;

        $pagination .= "<div class=\"pagination\"";

        if (@$margin || @$padding) 
        {
            $pagination .= " style=\"";
            if ($margin)
                $pagination .= "margin: $margin;";
            if ($padding)
                $pagination .= "padding: $padding;";
            $pagination .= "\"";
        }
        if ($this->show_total_records)
            $pagination .= "><span class='tableStandardBold' style='margin-right:50px;'> Total Number of record(s) found: " . $this->total_rows . " </span>";
        else
            $pagination .= ">";


        if ($this->getLastPage() > 1) 
        {            
            if ($page > 1)
            {
                $pagination .= "<a href={$this->url}1>« first</a>";
                $pagination .= "<a href=$this->url$prev>‹ prev</a>";
            }
            else
            {
                $pagination .= "<span class=\"disabled\">« first</span>";
                $pagination .= "<span class=\"disabled\">‹ prev</span>";
            }


            if ($this->getLastPage() < $this->show_ellipsis) 
            {
                for ($counter = 1; $counter <= $this->getLastPage(); $counter++) 
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">" . $counter . "</span>";
                    else
                        $pagination .= "<a href=$this->url$counter>" . $counter . "</a>";
                }
            }
            elseif ($this->getLastPage() >= $this->show_ellipsis)
            {
                if ($page < 4) 
                {
                    for ($counter = 1; $counter < 6; $counter++) 
                    {
                        if ($counter == $page)
                            $pagination .= "<span class=\"current\">" . $counter . "</span>";
                        else
                            $pagination .= "<a href=\"$this->url$counter\">" . $counter . "</a>";
                    }
                    $pagination .= "...";
                    $pagination .= "<a href=$this->url$lpm1>" . $lpm1 . "</a>";
                    $pagination .= "<a href={$this->url}{$this->getLastPage()}>" . $this->getLastPage() . "</a>";
                }
                elseif ($this->getLastPage() - 3 > $page && $page > 1) 
                {
                    $pagination .= "<a href={$this->url}1>1</a>";
                    $pagination .= "<a href={$this->url}2>2</a>";
                    $pagination .= "...";
                    for ($counter = $page - 1; $counter <= $page + 1; $counter++) {
                        if ($counter == $page)
                            $pagination .= "<span class=\"current\">" . $counter . "</span>";
                        else
                            $pagination .= "<a href=$this->url$counter>" . $counter . "</a>";
                    }
                    $pagination .= "...";
                    $pagination .= "<a href=$this->url$lpm1>$lpm1</a>";
                    $pagination .= "<a href={$this->url}{$this->getLastPage()}>" . $this->getLastPage() . "</a>";
                }
                else 
                {
                    $pagination .= "<a href={$this->url}1>1</a>";
                    $pagination .= "<a href={$this->url}2>2</a>";
                    $pagination .= "...";
                    for ($counter = $this->getLastPage() - 4; $counter <= $this->getLastPage(); $counter++) 
                    {
                        if ($counter == $page)
                            $pagination .= "<span class=\"current\">" . $counter . "</span>";
                        else
                            $pagination .= "<a href=$this->url$counter>" . $counter . "</a>";
                    }
                }
            }

            if ($page < $counter - 1)
            {
                $pagination .= "<a href=$this->url$next>next ›</a>";
                $pagination .= "<a href={$this->url}{$this->getLastPage()}>last »</a>";
            }
            else
            {
                $pagination .= "<span class=\"disabled\">next ›</span>";
                $pagination .= "<span class=\"disabled\">last »</span>";
            }

            if ($this->show_dropdown)
                $pagination .= "<span class='tableStandardBold' style='margin-left:20px;'>Go to page:  " . $this->generateDropdown() . "</span>\n";

            if ($this->show_page_no)
            {
                $page = 1;
                if (isset($this->page_no) && $this->page_no != "")
                    $page = $this->page_no;
                $pagination .= "<span class='tableStandardBold' style='margin-left:20px;'> Page " . $page . " of " . $this->getLastPage() . "</span>\n";
            }

            $pagination .= "</div>\n";
        }
        return $pagination;
    }

}

?>

Related Post