search
HomeBackend DevelopmentPHP TutorialPHP从0单排(十四)数据分页显示的原理及实现

PHP从零单排(十四)数据分页显示的原理及实现

分页显示是WEB编程中最频繁处理的环节之一。所谓分页显示,就是通过程序将结果集一段一段的来显示。实现分页显示,需要两个初始参数:每页显示多少记录和当前是第几页。再加上完整的结果集,就可以实现数据的分页显示。至于其他功能,比如上一页、下一页等均可以根据以上信息加以处理得到。

要取得某表中的前10条记录,可以使用如下SQL语句:

SELECT * FROM a_table LIMIT 0,10

要查找第11到第20条记录,使用的SQL语句如下所示:

SELECT * FROM a_table LIMIT 10,10

如要查找第21条到第30条记录,使用的SQL语句如下所示:

SELECT * FROM a_table LIMIT 20,10

以上SQL语句可以看出,每次取10条记录,相当于每个页面显示10条数据,而每次所要取得记录的起始位置和当期页数之间存在着这样的关系:起始位置=(当前页数-1)*每页要显示的记录数。如果以变量$page_size表示每页显示的记录数,以变量$cur_page表示当前页数,那么上述可以用下面所示的SQL语句模板归纳:

select * from table limit ($cur_page-1)*$page_size,$page_size;

这样,就得到了分页情况下获取数据的SQL语句。其中$page_size可以根据实际情况制定为一个定值,实际开发中,当前页面$cur_page可以由参数传入。另外,数据要显示的总页数,可以在记录总数和每页显示的记录数之间通过计算获得。比如,如果总记录数除以每页显示的记录数后,没有余数,那么总页数就是这二者之商。

<?php $host='localhost';$user_name='root';$password='helloworld';$conn=mysql_connect($host,$user_name,$password);if(!$conn){	die('FAIL!'.mysql_error());}mysql_select_db('test');if(isset($_GET['page'])){	$page=$_GET['page'];}else{	$page=1;}$page_size=2;$sql='select * from users';$result=mysql_query($sql);$total=mysql_num_rows($result);if($total){	if($total<$page_size)	$page_count=1;	if($total%$page_size)	{		$page_count=(int)($total/$page_size)+1;	}	else	{		$page_count=$total/$page_size;	}}else{	$page_count=0;}$turn_page='';if($page==1){	$turn_page.='Index | Before |';}else{	$turn_page.='<a href=13-8.php?page=1>Index | <a href="13-8.php?page='.(%24page-1).'">Before</a> |';}if($page==$page_count || $page_count==0){	$turn_page.='Next | Last';}else{	$turn_page.='<a href="13-8.php?page='.(%24page+1).'"> Next </a> | <a href="13-8.php?page='.%24page_count.'"> Last </a>';}$sql='select id,name,sex,age from users limit '.($page-1)*$page_size.','.$page_size;$result=mysql_query($sql) OR die ("<br>ERROR:<b>".mysql_error()."</b><br>SQL:".$sql);?><title>13-8.php</title>

**********************

POST GET ,是提交表单的两种方式,GET传值就用$_GET获取,POST提交表单就用$_POST
post与get的区别是一个在地址栏显示参数,另一个不显示

举个例子,如果你登录的时候用get方式,那么你的值就会在地址栏上显示,这样就无安全性可言
而你在搜索或者有页码的时候 用post把参数在地址栏上隐藏起来,这样就毫无意义

而用$_GET可以获得浏览器地址栏上的参数的值(?问号后面的一串字符),比如www.baidu.com/s?wd=123,那么你用$_GET,就可以获取参数(你可以理解为事件,动作,或者参数,该值在传递表单时与input的name一致)为wd的值123,多个参数用&符连接,比如?an=0&si=5理解为an参数的值为0与si参数的值为5。

**********************

打个比方说,你输入一个地址叫 www.iron-feet.cn/?page=2
$_GET["page"]就是获得地址上这个page的值,即得到2

ID
Name
Sex
Age
          
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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools