PHP application pagination Display production detailed explanation _php Foundation

Source: Internet
Author: User
Tags pear prev

1. Preface

Paging display is a very common way to browse and display large amounts of data, one of the most frequently handled events in Web programming. For the veteran of Web programming, writing this code is as natural as breathing, but for beginners, often on this issue does not feel a clue, so specially to write this article on this issue for detailed explanation, and strive to let the reading of this article after reading the principle of pagination and the realization of the method to understand. This article is for beginners to read, and all sample code is written using PHP.

2. Principle

The so-called paging display, that is, the result set in the database for the artificial section of the display, here need two initial parameters:

How many records per page ($PageSize)?
What is the current page ($CurrentPageID)?

Now just give me one more result set, and I can show a specific piece of results.

As for other parameters, such as: the previous page ($PreviousPageID), the next page ($NextPageID), the total number of pages ($numPages), etc., can be based on these things in front.

Take the MySQL database for example, if you want to intercept a piece of content from a table, SQL statements can be used: SELECT * FROM table limit offset, rows. Take a look at the following set of SQL statements and try to find the gauge in them.

First 10 records: SELECT * FROM table limit 0,10
11th to 20th record: SELECT * FROM table limit 10,10
21st to 30th Record: SELECT * FROM table limit 20,10
......

This set of SQL statements is actually a SQL statement that takes every page of data from the table when $pagesize=10, and we can summarize this template:

SELECT * FROM table limit ($CurrentPageID-1) * $PageSize, $PageSize

Take this template to the corresponding value and the top of the group of SQL statements in contrast to see if that is the case. The most important thing to do is to get the data, the rest is just passing the parameters, constructing the appropriate SQL statements and then using PHP to get the data from the database and display it. I'll explain this in concrete code.

3. Simple code

Please read the following code in detail, debug your own run once, it is best to modify it once, plus its own functions, such as search and so on.

//Establish a database connection
$link = mysql_connect ("localhost", "Mysql_user", "Mysql_password")
or Die ("could not C" Onnect: ". Mysql_error ());
//Get current page
if (isset ($_get[' page ')) {
$page = intval ($_get[' page ');
}
else{
$page = 1;
}
//number per page
$PageSize = 10;
//Get total amount of data
$sql = "SELECT count (*) as amount from table";
$result = mysql_query ($sql);
$row = Mysql_fetch_ Row ($result);
$amount = $row [' Amount '];
//Count the total number of pages
if ($amount) {
if ($amount $page _size) {$page _count = 1;}//////If total data is less than $pagesize, then only one page
if ($amount% $page _size) {//Total amount of data divided by the remainder of the number of pages
$page _count = (int) ($amount/$page _size) + 1;///If there are more than one, then the page equals the total amount of data divided by the result of each page and then a
}else{
$p Age_count = $amount/$page _size; If there is no remainder, the number of pages equals the total amount of data divided by the results of each page (
}
}
else{
$page _count = 0;
}

Page links
$page _string = ';
if ($page = = 1) {
$page _string. = ' first page | previous page | ';
}
else{
$page _string. = ' first page | Previous page | ';
}
if ($page = = $page _count) | | ($page _count = 0)) {
$page _string. = ' next page | last ';
}
else{
$page _string. = ' next page | last ';
}
Gets the data and returns the result in a two-dimensional array format
if ($amount) {
$sql = "SELECT * from table ORDER BY id desc limit". ($page-1) * $page _size. ", $page _size";
$result = mysql_query ($sql);

while ($row = Mysql_fetch_row ($result)) {
$rowset [] = $row;
}
}else{
$rowset = Array ();
}
There is no code to display the results, which is not in the scope of the discussion, as long as a foreach can be used to display the result with a two-dimensional array.
? >

4, OO style code

The database connection in the following code is handled using the Pear DB Class

//FileName:Pager.class.php
//pagination class, which is used only to process the data structure, not to handle the work displayed
class Pager
{
var $PageSize; Number of pages per page
var $CurrentPageID;//Current Page
var $NextPageID;//Next
Var $PreviousPageID;//prev
var $numPages;//Total Number of pages
Var $numItems;//Total Records
Var $isFirstPage//Whether the first page
Var $isLastPage;//whether last page
var $sql;//sql Query

Function Pager ($option)
{
Global $db;
$this->_setoptions ($option);    
//Total number of bars
if (!isset ($this->numitems))
{
$res = $db->query ($this->sql);
$this->numitems = $res->numrows ();
}
//Total pages
if ($this->numitems > 0)
{
if ($this->numitems $this->pagesize) {$this->num Pages = 1;
if ($this->numitems% $this->pagesize)
{
$this->numpages= (int) ($this->numitems/$this->pagesiz e) + 1;    
}
Else
{
$this->numpages = $this->numitems/$this->pagesize;
   
}
Else
{
$this->numpages = 0;
}

Switch ($this->currentpageid)
{
Case $this->numpages = 1:
$this->isfirstpage = true;
$this->islastpage = true;
Break
Case 1:
$this->isfirstpage = true;
$this->islastpage = false;
Break
Case $this->numpages:
$this->isfirstpage = false;
$this->islastpage = true;
Break
Default
$this->isfirstpage = false;
$this->islastpage = false;
}

if ($this->numpages > 1)
{
if (! $this->islastpage) {$this->nextpageid = $this->currentpageid + 1;}
if (! $this->isfirstpage) {$this->previouspageid = $this->currentpageid-1}
}

return true;
}

/***
*
* Returns the database connection of the result set
* You can use this method to get the database connection directly when the result set is larger, and then traverse outside the class, which is less expensive
* If the result set is not very large, you can get the result of the two-dimensional array format directly using the Getpagedata method
* Getpagedata method is also called this method to obtain the result
*
***/

function Getdatalink ()
{
if ($this->numitems)
{
Global $db;

$PageID = $this->currentpageid;

$from = ($PageID-1) * $this->pagesize;
$count = $this->pagesize;
$link = $db->limitquery ($this->sql, $from, $count); Using the Pear Db::limitquery method to guarantee database compatibility

return $link;
}
Else
{
return false;
}
}

/***
*
* Returns the result set in a two-dimensional array format
*
***/

function Getpagedata ()
{
if ($this->numitems)
{
if ($res = $this->getdatalink ())
{
if ($res->numrows ())
{
while ($row = $res->fetchrow ())
{
$result [] = $row;
}
}
Else
{
$result = Array ();
}

return $result;
}
Else
{
return false;
}
}
Else
{
return false;
}
}

function _setoptions ($option)
{
$allow _options = Array (
' PageSize ',
' Currentpageid ',
' SQL ',
' NumItems '
);

foreach ($option as $key => $value)
{
if (In_array ($key, $allow _options) && ($value!= null))
{
$this-> $key = $value;
}
}

return true;
}
}
? >
<?php
FileName:test_pager.php
This is a simple example code that omits the code to establish a database connection using the Pear DB Class
Require "Pager.class.php";
if (Isset ($_get[' page '))
{
$page = (int) $_get[' page '];
}
Else
{
$page = 1;
}
$sql = "SELECT * from table order by id";
$pager _option = Array (
"SQL" => $sql,
"PageSize" => 10,
"Currentpageid" => $page
);
if (Isset ($_get[' NumItems '))
{
$pager _option[' numitems '] = (int) $_get[' NumItems '];
}
$pager = @new Pager ($pager _option);
$data = $pager->getpagedata ();
if ($pager->isfirstpage)
{
$turnover = "Home | prev |";
}
Else
{
$turnover = "<a Href= ' page=1&numitems=". $pager->numitems. "' > home </a> |<a href= '? page= '. $pager-> Previouspageid. " &numitems= ". $pager->numitems." ' > Previous page </a> | ";
}
if ($pager->islastpage)
{
$turnover. = "Next page | last";
}
Else
{
$turnover. = "<a Href= ' page=". $pager->nextpageid. " &numitems= ". $pager->numitems." ' > next page </a> |<a href= '? page= '. $pager->numpages. " &numitems= ". $pager->numitems." ' > last </a> ";
}
? >

There are two places to note:

This class simply handles the data and is not responsible for the display, because I think it's a bit grudging to put the data processing and the display of the results in a class. Display when the situation and requirements vary, rather than their own according to the results of the class to deal with, a better way is based on this pager class to inherit a subclass of their own to display different pagination, such as Display user page list can:

Class Memberpager extends Pager
{
function Showmemberlist ()
{
Global $db;

$data = $this->getpagedata ();
Code to display results
// ......
}
}
Call
if (Isset ($_get[' page '))
{
$page = (int) $_get[' page '];
}
Else
{
$page = 1;
}
$sql = "SELECT * from members ' ORDER by ID";
$pager _option = Array (
"SQL" => $sql,
"PageSize" => 10,
"Currentpageid" => $page
);
if (Isset ($_get[' NumItems '))
{
$pager _option[' numitems '] = (int) $_get[' NumItems '];
}
$pager = @new Memberpager ($pager _option);
$pager->showmemberlist ();
? >

The second place to be explained is the compatibility of different databases, and the way in which a result is intercepted in different databases is not the same.

Mysql:select * FROM table limit offset, rows
Pgsql:select * FROM table limit m offset n
......

So you need to use the Limitquery method of the Pear DB class to get results inside the class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.