Home php教程 PHP源码 php 分页原理讲解

php 分页原理讲解

May 23, 2016 pm 04:40 PM
php

分页原理详解,其实各个语言的都差不多,主要是程序跟数据库的表达方式不一样。


在看本文之前,请确保你已掌握了PHP的一些知识以及MYSQL的查询操作基础哦。

作为一个Web程序,经常要和不计其数的数据打交道,比如会员的数据,文章数据,假如只有几十个会员那很好办,在一页显示就可以了,可是假如你的网站是几千甚至几十万会员的话,如果都在一页打开的话无论对浏览器还是观看者都是一种折磨,而且如果数据上亿,从数据库里查询一次的话,对服务器的压力是很大的,这不是正确的方法。

相信每个学习PHP的新手都会对分页这个东西感觉很头疼,不过有了默默的这一水帖,你肯定会拍拍脑袋说,嘿,原来分页竟然如此简单?的确,现在请深呼吸一口新鲜的空气,仔细的听默默给你一点一点的分解。

假设我们要处理1000条数据,要在每页中显示10条,这样的话就会分100页来显示,咱们先看一看在mysql里提取10条信息是如何操作的。

Select * from table limit 0,10

上面是一句很简单的mysql查询语句,它的作用是从一个名叫table的表里提取10条数据,并且把所有字段的值都获得。其中的limit 0,10的用法是:limit 开始点,要提取的数目

关键的地方就在这段“limit 0,10”,它其中的0是以0为起始点,后面的10则是显示10条数据,那么我们要以10为起始点,显示到第20条数据该怎么写呢?

可能很多大大会心直口快的说“limit 10,20”嘛!啊哦,这样可就错误了哦,正确的写法是“limit 10,10”它后面的参数并非是结束点而是要提取的数目 ,记住哦。

懂得了如何提取10条数据,那么提取1000条也就是做100次这种查询呀,就是说要做如下的查询:

Limit 0,10                 //第一页
Limit 10,10                //第二页
Limit 20,10                //第三页
Limit 30,10                //第四页
……
看出有什么规律了吗?没错,第一个参数每翻一页就增加10,可是第二个参数是不变的。
也就是说咱们设法根据页数来改变第一个参数的值 ,就可以进行分页显示数据了,怎么样,原理是不是很简单?

可是要怎么设法根据页数来改变第一个参数的值呢?首先,咱们要有一个页数的值,用url的GET方式获取。
比如index.php?page=18
相信大部分的大大对这个东西不陌生吧,这种url地址可是随处可见,其中的page参数的作用就是传入要显示的页数。

咱们通过一段代码来看一看究竟是如何实现的吧:

[php]

/*

Author:默默
Date :2006-12-03

*/

$page=isset($_GET['page'])?intval($_GET['page']):1; //这句就是获取page=18中的page的值,假如不存在page,那么页数就是1。
$num=10; //每页显示10条数据

$db=mysql_connect("host","name","pass"); //创建数据库连接
$select=mysql_select_db("db",$db); //选择要操作的数据库

/*
首先咱们要获取数据库中到底有多少数据,才能判断具体要分多少页,总页数 具体的公式就是
总数据数 除以 每页显示的条数,有余进一
也就是说10/3=3.3333=4 有余数就要进一。
*/

$total=mysql_num_rows(mysql_query("select * from table")); //查询数据的总数total
$pagenum=ceil($total/$num); //获得总页数 pagenum

//假如传入的页数参数apge 大于总页数 pagenum,则显示错误信息
If($page>$pagenum || $page == 0){
       Echo "Error : Can Not Found The page .";
       Exit;
}

$offset=($page-1)*$num;         //获取limit的第一个参数的值 offset ,假如第一页则为(1-1)*10=0,第二页为(2-1)*10=10。             (传入的页数-1) * 每页的数据 得到limit第一个参数的值

$info=mysql_query("select * from table limit $offset,$num ");   //获取相应页数所需要显示的数据
While($it=mysql_fetch_array($info)){
       Echo $it['name']."
";
}                                                              //显示数据

For($i=1;$i<=$pagenum;$i++){

$show=($i!=$page)?"$i":"$i";
       Echo $show." ";
}

/*显示分页信息,假如是当页则显示粗体的数字,其余的页数则为超连接,假如当前为第三页则显示如下
1 2 3 4 5 6
*/
?>
   [/php]
假如你仔细的读过上面的代码,把数据库连接和查询的表替换成你的,那么就能看见它的执行效果哦。

是不是很简单,只要动动脑筋,可以让它显示的更为个性化哦,给大家出一个小题,如何实现“首页 上一页 下一页 尾页”这种格式的分页呢?

OK,水帖灌完,收工。^_^ 默默小谈PHP&MYSQL分页原理及实现
===================================
总结:

原型:      Select * from table limit 0,10
程序:
select * from table limit $offset,$num ($offset取值是:传入的页面数-1     $num是每个页面显示的数据,多为固定常量值)

总分页数:总数据 每页显示的条数有余进一
    int totalPage=((totalCount%NUM)==0)?totalCount/NUM:totalCount/NUM+1;

limit用法limit 开始点,要提取的数目

不过要注意的是:一定要加上order by ,确定以上升或者下降的顺序来查询,不然在查询的时候会不知道从哪个方向开始查询。不过一定要注意顺序:正确的是select * from user order by id desc limit 0,10;

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles