search
HomeBackend DevelopmentPHP TutorialPaging source and paging class in php_PHP tutorial

The so-called paging display means that the result set in the database is artificially divided into sections for display. Two initial parameters are required here: How many records per page ($PageSize)?

What page is the current page ($CurrentPageID)?
Now just give me another result set and I can display a specific result.
As for other parameters, such as: previous page ($PReviousPageID), next page ($NextPageID), total number of pages ($numPages), etc., they can all be obtained based on the previous things.
Taking the MySQL database as an example, if you want to intercept a certain piece of content from the 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 the rules.
The first 10 records: select * from table limit 0,10
Records 11 to 20: select * from table limit 10,10
Records 21 to 30: select * from table limit 20,10

This set of sql statements is actually the sql statement for fetching data from each page of the table when $PageSize=10. We can summarize such a template:
select * from table limit ($CurrentPageID – 1) * $PageSize, $PageSize
Take this template and substitute the corresponding values ​​​​into the above set of SQL statements to see if that is the case. After solving the most important problem of how to obtain the data, all that is left is to pass the parameters, construct the appropriate SQL statement and then use PHP to obtain the data from the database and display it. Below I will explain it with specific code.
3. Simple code
Please read the following code in detail, debug and run it yourself, it is best to modify it and add your own functions, such as search, etc.
[php]

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

// 建立数据库连接
$link = mysql_connect(“localhost”, “mysql_user”, “mysql_passWord”)
or die(“Could not connect: ” . mysql_error());
// 获取当前页数
if( isset($_GET['page']) ){
$page = intval( $_GET['page'] );
}
else{
$page = 1;
}
// 每页数量
$PageSize = 10;
// 获取总数据量
$sql = “select count(*) as amount from table”;
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$amount = $row['amount'];
// 记算总共有多少页
if( $amount ){
if( $amount if( $amount % $page_size ){                                  //取总数据量除以每页数的余数
$page_count = (int)($amount / $page_size) + 1;           //如果有余数,则页数等于总数据量除以每页数的结果取整再加一
}else{
$page_count = $amount / $page_size;                      //如果没有余数,则页数等于总数据量除以每页数的结果
}
}
else{
$page_count = 0;
}
// 翻页链接
$page_string = ”;
if( $page == 1 ){
$page_string .= ‘第一页|上一页|’;
}
else{
$page_string .= ‘第一页|上一页|’;
}
if( ($page == $page_count) || ($page_count == 0) ){
$page_string .= ‘下一页|尾页’;
}
else{
$page_string .= ‘下一页|尾页’;
}
// 获取数据,以二维数组格式返回结果
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();
}
// 没有包含显示结果的代码,那不在讨论范围,只要用foreach就可以很简单的用得到的二维数组来显示结果
?>

// Establish database connection $link = mysql_connect(“localhost”, “mysql_user”, “mysql_passWord”) or die(“Could not connect: ” . mysql_error()); // Get the current page number if( isset($_GET['page']) ){ $page = intval( $_GET['page'] ); } else{ $page = 1; } //Number per page $PageSize = 10; // Get the total data volume $sql = “select count(*) as amount from table”; $result = mysql_query($sql); $row = mysql_fetch_row($result); $amount = $row['amount']; // Calculate how many pages there are in total if( $amount ){ if ($ amount & lt; $ page_size) {$ page_count = 1;} // If the total data amount is less than $ pageSize, then there is only one page if( $amount % $page_size ){                                                                                                                                                   $page_count = (int)($amount / $page_size) + 1;                        //If there is a remainder, the number of pages is equal to the total data amount divided by the number of pages, rounded up and plus one }else{ $ page_count = $ amount /$ page_size; // If there is no more number, the number of pages is equal to the total data volume divided by the results of each page } } else{ $page_count = 0; } // Page turning link $page_string = ”; if( $page == 1 ){ $page_string .= ‘First page|Previous page|’; } else{ $page_string .= 'First page|Previous page a>|'; } if( ($page == $page_count) || ($page_count == 0) ){ $page_string .= ‘next page|last page’; } else{ $page_string .= 'Next page| Last page'; } // Get data and return the result 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, so that is beyond the scope of discussion. You can simply use the obtained two-dimensional array to display the results using foreach ?>

PHP paginator production, automatically generates faceted page numbers, JS calls functions

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->pageCountpageCount;
//Check pageNo
           $this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;
$this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;

//Calculate offset
$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             for($i=0;$ipageCount;$i++){
                array_push($pageList,$i+1);
            }
        }else{
            if($this->pageNo                 for($i=0;$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 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;
    }
}

?>

-->

PHP调用

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


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

复制代码
$pageNo = $_GET['pageNo'];

if(empty($pageNo)){

} $pageData = News::getNewsPage($pageNo,$pageSize);        //取得总行数 $count = News::getNewsCount();         //创建分页器 $p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);      //生成页码 $pageViewString = $p->echoPageAsDiv();
http://www.bkjia.com/PHPjc/628968.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/628968.htmlTechArticle所谓分页显示,也就是将数据库中的结果集人为的分成一段一段的来显示,这里需要两个初始的参数:每页多少条记录($PageSize)? 当前是...
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),