PHP Paging details (with examples) _php tutorial

Source: Internet
Author: User
Tags pear
1. Preface
Pagination display is a very common way to browse and display large amounts of data, which is one of the most frequently handled events in Web programming. For the veteran of Web programming, writing this code is just as natural as breathing, but for beginners, often do not have a clue to this problem, so specially written this article on this issue to explain in detail, and strive to let the friends after reading this post after reading for the page display of the principle and implementation of the method have some understanding. 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 is artificially divided into a section of the display, here requires two initial parameters:
How many records per page ($PageSize)?
What is the current page ($CurrentPageID)?
Now just give me a result set and I can show a specific result.
For other parameters, such as the previous page ($PReviousPageID), the next page ($NextPageID), the total number of pages ($numPages), and so on, can be based on the front of these things.
For example, in MySQL database, if you want to intercept a piece of content from within a table, the SQL statement can be used: SELECT * FROM table limit offset, rows. Take a look at the following set of SQL statements and try to find out the rate of compliance.
Top 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 in the table when $pagesize=10, and we can summarize a template like this:
SELECT * FROM table limit ($CurrentPageID-1) * $PageSize, $PageSize
Take this template and replace the corresponding value with the set of SQL statements above to see if that's the case. Take care of the most important question of how to get the data, all that is left is to pass the parameters, construct the appropriate SQL statement, and then use PHP to retrieve the data from the database and display it. I'll use the specific code to illustrate the following.
3. Simple code
Please read the following code in detail, run your own debugging once, it is best to modify it once, plus your own features, such as search and so on.
Copy CodeThe code is as follows:
Establishing a database connection
$link = mysql_connect ("localhost", "Mysql_user", "Mysql_password")
Or Die ("Could Not connect:". Mysql_error ());
Get the current number of pages
if (Isset ($_get[' page ')) {
$page = intval ($_get[' page ');
}
else{
$page = 1;
}
Quantity per page
$PageSize = 10;
Get Total data volume
$sql = "SELECT count (*) as amount from table";
$result = mysql_query ($sql);
$row = Mysql_fetch_row ($result);
$amount = $row [' Amount '];
Count how many pages there are in total
if ($amount) {
if ($amount < $page _size) {$page _count = 1;}//If the total data volume is less than $pagesize, then there is only one page
if ($amount% $page _size) {//Take the total amount of data divided by the remainder of each page
$page _count = (int) ($amount/$page _size) + 1; If there is an excess, the number of pages equals the total amount of data divided by the result of each page plus one
}else{
$page _count = $amount/$page _size; If there is no remainder, the number of pages equals the total data amount divided by the result of each page
}
}
else{
$page _count = 0;
}

Page link
$page _string = ";
if ($page = = 1) {
$page _string. = ' first page | prev | ';
}
else{
$page _string. = ' first page | prev | ';
}
if ($page = = $page _count) | | ($page _count = = 0)) {
$page _string. = ' next page | last ';
}
else{
$page _string. = ' next page | last ';
}
Get data to return results in 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, that is not the scope of the discussion, as long as a foreach can be used to easily use the resulting two-dimensional array to display the results
?>

4. oo Style code
The database connection in the following code is handled using the Pear DB Class
Copy CodeThe code is as follows:
FileName:Pager.class.php
Paging class, which is used only to process data structures and is not responsible for working with the display
Class Pager
{
var $PageSize; Number of pages per page
var $CurrentPageID; Current number of pages
var $NextPageID; Next page
var $PreviousPageID; Previous page
var $numPages; Total pages
var $numItems; Total Record Count
var $isFirstPage; Whether the first page
var $isLastPage; Whether the last page
var $sql; SQL query Statements

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->numpages = 1;}
if ($this->numitems% $this->pagesize)
{
$this->numpages= (int) ($this->numitems/$this->pagesize) + 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 for the result set
* When the result set is relatively large, you can use this method to get the database connection directly, 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
* The Getpagedata method also calls this method to get 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); Ensuring database compatibility with the Pear Db::limitquery method

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;
}
}
?>
FileName:test_pager.php
This is a simple example code that omits the code that uses the Pear DB class to establish a database connection
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 Page | prev |";
}
Else
{
$turnover = "NumItems." > Home | Previouspageid. " &numitems= ". $pager->numitems." > Prev | ";
}
if ($pager->islastpage)
{
$turnover. = "Next page | last";
}
Else
{
$turnover. = "Nextpageid." &numitems= ". $pager->numitems." > next page |numpages. " &numitems= ". $pager->numitems." > Last ";
}
?>

There are two places to be explained:
This class only handles the data and is not responsible for the display, because I think it is a little reluctant to put the data processing and the display of the results into a class. When the situation and requirements are changeable, it is better to treat them according to the results given by the class, and the best way to do this is to inherit a subclass from the pager class to display different pagination, such as displaying a user page list:

Copy the Code code as follows:
Class Memberpager extends Pager
{
function Showmemberlist ()
{
Global $db;

$data = $this->getpagedata ();
Code to display the result
// ......
}
}
Call
if (Isset ($_get[' page '))
{
$page = (int) $_get[' page ';
}
Else
{
$page = 1;
}
$sql = "SELECT * from the 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 area to be explained is the compatibility of different databases, and it is not the same to intercept a result in different databases.
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 the results in the class.

OK, finish writing.

http://www.bkjia.com/PHPjc/824950.html www.bkjia.com true http://www.bkjia.com/PHPjc/824950.html techarticle 1. Foreword pagination Display is a very common way to browse and display large amounts of data, which is one of the most frequently handled events in Web programming. For the veteran of Web programming, write this generation ...

  • 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.