Summary of commonly used paging classes in PHP_PHP tutorial

WBOY
Release: 2016-07-20 11:11:30
Original
947 people have browsed it

Pagination is by far the best way to display large numbers of results. With the help of the following codes, developers can display large amounts of data in multiple pages. On the Internet, paging is generally used for search results or browsing all information

php basic paging

The code is as follows Copy code
 代码如下 复制代码

// database connection info
$conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('dbname',$conn) or trigger_error("SQL", E_USER_ERROR);

// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if

// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "
";
} // end while

/****** build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " << ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " < ";
} // end if

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [$x] ";
// if not current page...
} else {
// make it a link
echo " $x ";
} // end else
} // end if
} // end for

// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " > ";
// echo forward link for lastpage
echo " >> ";
} // end if
/****** end build pagination links ******/
?>

// database connection info
$conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('dbname',$conn) or trigger_error("SQL" , E_USER_ERROR);<🎜><🎜>// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];<🎜><🎜>// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);<🎜><🎜>// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if<🎜>< 🎜>// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages ;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if<🎜><🎜>// the offset of the list, based on current page
$offset = ($currentpage - 1 ) * $rowsperpage;<🎜><🎜>// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query( $sql, $conn) or trigger_error("SQL", E_USER_ERROR);<🎜><🎜>// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "
";
} // end while/****** build the pagination links ******/
// range of num links to show
$range = 3;// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " << ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " < ";
} // end if// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < ; (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x < ;= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don' t make a link
echo " [$x] ";
// if not current page...
} else {
// make it a link
echo " $x ";
} // end else
} // end if
} // end for// if not on last page, show forward and last page links
if ($currentpage != $totalpages ) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " > ";
// echo forward link for lastpage
echo " >> ";
} // end if
/****** end build pagination links ******/
? >

Let’s first look at a commonly used PHP paging class

The code is as follows Copy the code

< ?php
/*
Place code to connect to your DB here.
*/
include('config.php'); // include your code to connect to DB.

 $tbl_name="";  //your table name
 // How many adjacent pages should be shown on each side?
 $adjacents = 3;
 
 /*
    First get total number of rows in data table.
    If you have a WHERE clause in your query, make sure you mirror it here.
 */
 $query = "SELECT COUNT(*) as num FROM $tbl_name";
 $total_pages = mysql_fetch_array(mysql_query($query));
 $total_pages = $total_pages[num];
 
 /* Setup vars for query. */
 $targetpage = "filename.php";  //your file name  (the name of this file)
 $limit = 2;         //how many items to show per page
 $page = $_GET['page'];
 if($page)
  $start = ($page - 1) * $limit;    //first item to display on this page
 else
  $start = 0;        //if no page var is given, set start to 0
 
 /* Get data. */
 $sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
 $result = mysql_query($sql);
 
 /* Setup page vars for display. */
 if ($page == 0) $page = 1;     //if no page var is given, default to 1.
 $prev = $page - 1;       //previous page is page - 1
 $next = $page + 1;       //next page is page + 1
 $lastpage = ceil($total_pages/$limit);  //lastpage is = total pages / items per page, rounded up.
 $lpm1 = $lastpage - 1;      //last page minus 1
 
 /*
  Now we apply our rules and draw the pagination object.
  We're actually saving the code to a variable in case we want to draw it more than once.
 */
 $pagination = "";
 if($lastpage > 1)
 { 
  $pagination .= "

n";  
 }
?>

   while($row = mysql_fetch_array($result))
  {
 
  // Your while loop here
 
  }
 ?>


 


Example

The code is as follows Copy code

class PageView{
/**page number**/
public $pageNo = 1;
/**Page size**/
public $pageSize = 20;
/** How many pages in total**/
public $pageCount = 0;
/**Total number of records**/
public $totalNum = 0;
/**Offset, starting line of current page**/
public $ offSet = 0;
/**Data per page**/
public $pageData = array();

/**Is there a previous page**/
public $hasPrePage = true;
/**Is there a next page**/
public $hasNextPage = true;

public $pageNoList = array();

public $jsFunction ='jsFunction';
/**
*
* @param unknown_type $count Total number of rows
* @param unknown_type $size Paging size
* @param unknown_type $string
*/
public function __construct($count=0, $size=20,$pageNo=1,$pageData =array(),$jsFunction='jsFunction'){

$this->totalNum = $count;//Total number of records
$this->pageSize = $size;//Size of each page
$this->pageNo = $pageNo;
//Calculate the total number of pages
$this->pageCount = ceil($this->totalNum/$this->pageSize);
$this->pageCount = ($this->pageCount< ;=0)?1:$this->pageCount;
                                                                                                  ’
$this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;

$this->offset = ($this->pageNo - 1) * $this->pageSize;
//Calculate whether there is a previous page or a next page
$this-> hasPrePage = $this->pageNo == 1 ?false:true;

        $this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;
       
        $this->pageData = $pageData;
        $this->jsFunction = $jsFunction;
       
    }
    /**
* Paging algorithm
* @return
*/
    private function generatePageList(){
        $pageList = array();
        if($this->pageCount <= 9){
            for($i=0;$i<$this->pageCount;$i++){
                array_push($pageList,$i+1);
            }
        }else{
            if($this->pageNo <= 4){
                for($i=0;$i<5;$i++){
                    array_push($pageList,$i+1);
                }
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);

            }else if($this->pageNo > $this->pageCount - 4){
                array_push($pageList,1);
               
                array_push($pageList,-1);
                for($i=5;$i>0;$i--){
                    array_push($pageList,$this->pageCount - $i+1);
                }
            }else if($this->pageNo > 4 && $this->pageNo <= $this->pageCount - 4){
                array_push($pageList,1);
                array_push($pageList,-1);
               
                array_push($pageList,$this->pageNo -2);
                array_push($pageList,$this->pageNo -1);
                array_push($pageList,$this->pageNo);
                array_push($pageList,$this->pageNo + 1);
                array_push($pageList,$this->pageNo + 2);
               
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);
               
            }
        }
        return $pageList;
    }

    /***
* Create paging control
* @param
* @return String
*/
    public function echoPageAsDiv(){
        $pageList = $this->generatePageList();
       
        $pageString ="

");
        return $pageString;
    }
}

?>

css代码

 代码如下
 代码如下 复制代码

复制代码

 代码如下 复制代码

    $pageNo = $_GET['pageNo'];
        if(empty($pageNo)){
            $pageNo = 1;
        }
        //分页数据
        $pageData = News::getNewsPage($pageNo,$pageSize);
       //取得总行数
        $count = News::getNewsCount();
        //创建分页器
        $p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);
     //生成页码
        $pageViewString = $p->echoPageAsDiv();


在php页面中的调用方法
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!