How PHP achieves webpage paging effect-php Tutorial

Source: Internet
Author: User
Tags php website
In the PHP website, there are many requirements for implementing pagination in PHP, which are mainly used to read novels.

The functions are as follows:

Several functions need to be called for paging using SQL queries. for details, see the script:
1. pager. class. php

Class pager {
Public $ SQL; // SQL query statement
Public $ datanum; // query the total number of data records
Public $ page_size; // number of records displayed on each page
Protected $ _ errstr;
Protected $ _ conn;
Protected $ _ query_id;

Public function query ($ query) // This function is faulty. you can skip this function for the moment.
{
$ Ret = false;
If (! Empty ($ query )){
If ($ this-> _ conn = false |! Is_resource ($ this-> _ conn )){
WarningLog (_ METHOD _. ': query SQL with no connection', true );
Return false;
}
$ This-> _ query_id = @ mysql_query ($ query, $ this-> _ conn );
If ($ this-> _ query_id === false ){
$ This-> _ errstr = @ mysql_error ();
$ Ret = false;
} Else {
$ This-> _ errstr = 'success ';
$ Ret = $ this-> _ query_id;
}
}
$ Msg = ($ ret = false )? 'False': strval ($ ret );
DebugLog (_ METHOD _. ": [$ msg] returned for SQL query [$ query]");
Return $ ret;
}
Function _ construct ($ SQL, $ page_size ){
$ Result = mysql_query ($ SQL );
$ Datanum = mysql_num_rows ($ result );
$ This-> SQL = $ SQL;
$ This-> datanum = $ datanum;
$ This-> page_size = $ page_size;
}

// Current page number
Public function page_id (){
If ($ _ SERVER ['query _ string'] = ""){
Return 1;
} Elseif (substr_count ($ _ SERVER ['query _ string'], "page_id =") = 0 ){
Return 1;
} Else {
Return intval (substr ($ _ SERVER ['query _ string'], 8 ));
}
}

// Remaining url value
Public function url (){
If ($ _ SERVER ['query _ string'] = ""){
Return "";
} Elseif (substr_count ($ _ SERVER ['query _ string'], "page_id =") = 0 ){
Return "&". $ _ SERVER ['query _ string'];
} Else {
Return str_replace ("page_id =". $ this-> page_id (), "", $ _ SERVER ['query _ string']);
}
}

// Total number of pages
Public function page_num (){
If ($ this-> datanum = 0 ){
Return 1;
} Else {
Return ceil ($ this-> datanum/$ this-> page_size );
}
}
// Database query offset
Public function start (){
Return ($ this-> page_id ()-1) * $ this-> page_size;
}

// Data output
Public function sqlquery (){
Return $ this-> SQL. "limit". $ this-> start (). ",". $ this-> page_size;
}

// Get the current file name
Private function php_self (){
Return $ _ SERVER ['php _ SELF '];
}

// Previous Page
Private function pre_page (){
If ($ this-> page_id () = 1) {// The number of pages equals 1
Return "php_self ()."? Page_id = 1 ". $ this-> url ()."> Previous Page ";
} Elseif ($ this-> page_id ()! = 1) {// The page number is not equal to 1
Return "php_self ()."? Page_id = ". ($ this-> page_id ()-1). $ this-> url ()."> Previous Page ";
}
}

// Display the page
Private function display_page (){
$ Display_page = "";
If ($ this-> page_num () <= 10) {// page smaller than 10
For ($ I = 1; $ I <= $ this-> page_num (); $ I ++) // The page is displayed cyclically.
$ Display_page. = "php_self ()."? Page_id = ". $ I. $ this-> url ()."> ". $ I ."";
Return $ display_page;
} Elseif ($ this-> page_num ()> 10) {// more than 10 pages
If ($ this-> page_id () <= 6 ){
For ($ I = 1; $ I <= 10; $ I ++) // The page is displayed cyclically.
$ Display_page. = "php_self ()."? Page_id = ". $ I. $ this-> url ()."> ". $ I ."";
Return $ display_page;
} Elseif ($ this-> page_id ()> 6) & ($ this-> page_num ()-$ this-> page_id ()> = 4 )){
For ($ I = $ this-> page_id ()-5; $ I <= $ this-> page_id () + 4; $ I ++) // The page is displayed cyclically
$ Display_page. = "php_self ()."? Page_id = ". $ I. $ this-> url ()."> ". $ I ."";
Return $ display_page;
} Elseif ($ this-> page_id ()> 6) & ($ this-> page_num ()-$ this-> page_id () <4 )){
For ($ I = $ this-> page_num ()-9; $ I <= $ this-> page_num (); $ I ++) // The page is displayed cyclically
$ Display_page. = "php_self ()."? Page_id = ". $ I. $ this-> url ()."> ". $ I ."";
Return $ display_page;
}
}
}

// Next page
Private function next_page (){
If ($ this-> page_id () <$ this-> page_num () {// The number of pages is less than the total number of pages
Return "php_self ()."? Page_id = ". ($ this-> page_id () + 1). $ this-> url ()."> Next Page ";
} Elseif ($ this-> page_id () = $ this-> page_num () {// The number of pages equals to the total number of pages
Return "php_self ()."? Page_id = ". $ this-> page_num (). $ this-> url ()."> Next Page ";
}
}

// Set paging information
Public function set_page_info (){
$ Page_info = "total". $ this-> datanum. "items ";
$ Page_info. = "php_self ()."? Page_id = 1 ". $ this-> url ()."> homepage ";
$ Page_info. = $ this-> pre_page ();
$ Page_info. = $ this-> display_page ();
$ Page_info. = $ this-> next_page ();
$ Page_info. = "php_self ()."? Page_id = ". $ this-> page_num (). $ this-> url ()."> last page ";
$ Page_info. = "". $ this-> page_id (). "/". $ this-> page_num (). "page ";
Return $ page_info;
}

}
?>
2. Script 2:
// Class usage
// Read the paging class
Include ("pager. class. php ");
// Database Connection Initialization
// $ Db = new mysql ();
$ Impeach_host = '10. 81.43.139 ';
$ Impeach_usr = 'vmtest15 ';
$ Impeach_passwd = 'vmtest15 ';
$ Impeach_name = 'ufeature ';
$ Impeach_con = mysql_connect ($ impeach_host, $ impeach_usr, $ impeach_passwd) or
Die ("Can't connect". mysql_error ());
Mysql_select_db ($ impeach_name, $ impeach_con );
// This is an SQL query statement and the query result is obtained.
$ SQL = "select word from ufeature. spam_accuse_word_list where flag = '0 '";
// Page initialization
$ Page = new pager ($ SQL, 20 );
// 20 is the number displayed on each page
// $ Res_1 = mysql_query ($ SQL) or
// Die ("Can't get result". mysql_error ());

$ Result = mysql_query ($ page-> sqlquery ());
While ($ info = mysql_fetch_array ($ result, MYSQL_ASSOC )){

// While ($ info = mysql_fetch_array ($ res_1, MYSQL_ASSOC )){
Echo $ info ["word"]."
";
}
// Page number index
Echo $ page-> set_page_info ();



?>
2. ajax

1. First, understand the limit usage in SQL statements.

SELECT * FROM table ...... Limit start position, number of operations (where the start position starts from 0)

Example:

Take the first 20 records: SELECT * FROM table ...... Limit 0, 20
Obtain 20 records FROM 11th: SELECT * FROM table ...... Limit 10, 20

LIMIT n is equivalent to LIMIT 0, n.

For example, select * from table LIMIT 5; // return the first five rows, the same as select * from table LIMIT

2. paging principle

The so-called paging display, that is, the result set in the database, is displayed in a segment

How to segment, the current segment (the number of lines per page, and the number of pages next)

First 10 records: select * from table limit 0, 10
11th to 20 records: select * from table limit 10, 10
21st to 30 records: select * from table limit 20, 10

Paging formula:

(Current page-1) X number of entries per page, number of entries per page
Select * from table limit ($ Page-1) * $ PageSize, $ PageSize

3. $ _ SERVER ["REQUEST_URI"] function

A type of predefined SERVER variables. all variables starting with $ _ SERVER are called SERVER variables.

REQUEST_URI is used to obtain the current URI, which is the complete address path after the domain name.

Example:

The current page is: http://www.test.com/home.php? Id = 23 & cid = 22

Echo $ _ SERVER ["REQUEST_URI"]

Result:/home. php? Id = 23 & cid = 22

4. parse_url () parses the URL function.

Parse_url () is a function that parses a URL into an array with a fixed key value.

Example
$ Ua = parse_url ("http: // username: password @ hostname/path? Arg = value # anchor ");
Print_r ($ ua );
Result:

Array
(
[Scheme] => http; protocol
[Host] => hostname; host domain name

[User] => username; user
[Pass] => password; password
[Path] =>/path; path
[Query] => arg = value; obtain the parameter

[Fragment] => anchor;
)


5. code example

The page for this message is divided into three parts: database design, connection page, and display page.

(1) design a database

The database name is bbs. there is a data table named message, which contains the title, lastdate, user, content and other fields, indicating the message title, message date, message recipient, and message content.

(2) connection page

$ Conn = @ mysql_connect ("localhost", "root", "123456") or die ("database link error ");
Mysql_select_db ("bbs", $ conn );
Mysql_query ("set names 'gbk'"); // use GBK Chinese encoding;

// Convert spaces and line breaks into HTML parses

Function htmtocode ($ content ){
$ Content = str_replace ("\ n ","
", Str_replace (" "," ", $ content); // Two str_replace nesting

Return $ content;
}

// $ Content = str_replace ("'", "'", $ content );
// Htmlspecialchars ();

?>

(3) display page

Include ("conn. php ");

$ Pagesize = 2; // set to display 2 records per page
$ Url = $ _ SERVER ["REQUEST_URI"];
$ Url = parse_url ($ url );
$ Url = $ url [path];


$ Numq = mysql_query ("SELECT * FROM 'message "');
$ Num = mysql_num_rows ($ numq );

If ($ _ GET [page]) {
$ Pageval = $ _ GET [page];
$ Page = ($ pageval-1) * $ pagesize;
$ Page. = ',';
}
If ($ num> $ pagesize ){
If ($ pageval <= 1) $ pageval = 1;

Echo "$ num total ".
"Next page of the previous page ";
}
$ SQL = "SELECT * FROM 'message' limit $ page $ pagesize ";
$ Query = mysql_query ($ SQL );

While ($ row = mysql_fetch_array ($ query )){
?>













Title: Time:
User:
Content:

}
?>
(4) Last display


Method 3:

Script
Function viewpage (p ){
If (window. XMLHttpRequest ){
Var xmlReq = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
Var xmlReq = new ActiveXObject ('Microsoft. xmlhttp ');
}
Var formData = "page =" + p;
XmlReq. onreadystatechange = function (){
If (xmlReq. readyState = 4 ){
Document. getElementByIdx_x ('content2'). innerHTML = xmlReq. responseText;
}
}
XmlReq. open ("post", "pai_list.php", true );
XmlReq. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
XmlReq. send (formData );
Return false;
}
Script

Script 2:


Header ("Content-Type: text/html; charset = GB2312 ");
$ Pagesize = 10;
// Echo $ _ POST ['Page'];
$ Result = mysql_query ("Select count (DISTINCT region name) FROM". TBL_HOTELS );
$ Myrow = mysql_fetch_array ($ result );
$ Numrows = $ myrow [0];

$ Pages = intval ($ numrows/$ pagesize );
If ($ numrows % $ pagesize)
$ Pages ++;
If (isset ($ _ POST ['Page']) {
$ Page = intval ($ _ POST ['Page']);
}
Else {
// Set it to the first page
$ Page = 1;
}
$ First = 1;
$ Prev = $ page-1;
$ Next = $ page + 1;
$ Last = $ pages;
// Calculate the record offset
$ Offset = $ pagesize * ($ page-1 );
// Read the specified number of records
$ Result = mysql_query ("select 'Partition name', count (*) from". TBL_HOTELS. "group by 'Partition name' order by id desc limit $ offset, $ pagesize ");
$ Num = mysql_num_rows ($ result );
While ($ row = mysql_fetch_array ($ result, MYSQL_NUM )){
$ Pipeline name [] = $ row [0];
$ Countpeople [] = $ row [1];
}
For ($ a = 0; $ a <$ num; $ a ++)
{
// $ Result = mysql_query ("select count (title) from ". TBL_Comments. "where 'title' = \"". $ title [$ a]. "\"");
// $ Row = mysql_fetch_row ($ result );
Echo"








\ N ";Echo" \ N ";Echo" \ N ";Echo" \ N ";Echo" \ N ";Echo" \ N ";Echo" \ N ";Echo"
\ N ";
// Rating_bar ($ title [$ a], 5 );
Echo"
$ Pipeline name [$ a] \ n ";
Echo"
\ N ";
Echo "recommended users: ($ countpeople [$ a]) | \ n ";
Echo"Average score:(". $ Count.") | number of comments :()\ N ";
Echo"
\ N ";
}
Echo"
Echo "border = 0> ";
Echo"";
Echo "";
Echo"

". $ Page." page/total ". $ pages." page | total ". $ numrows." | ";
If ($ page> 1) echo "homepage | ";
If ($ page> 1) echo "previous page | ";
If ($ page <$ pages) echo "next page | ";
If ($ page <$ pages) echo "last page ";
Echo "toPage";
Echo"

";

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.