Home Backend Development PHP Tutorial PHP和MySQL分页显示实例分析_PHP

PHP和MySQL分页显示实例分析_PHP

Jun 01, 2016 pm 12:31 PM
echo p page rs analyze Example show Record

Web开发是今后分布式程式开发的主流,通常的web开发都要涉及到与数据库打交道,客户端从服务器端读取通常都是以分页的形式来显示,一页一页的阅读起来既方便又美观。所以说写分页程序是web开发的一个重要组成部分,在这里,我们共同来研究分页程序的编写。

  一、分页程序的原理

  分页程序有两个非常重要的参数:每页显示几条记录($pagesize)和当前是第几页($page)。有了这两个参数就可以很方便的写出分页程序,我们以MySql数据库作为数据源,在mysql里如果要想取出表内某段特定内容可以使用的 T-SQL语句:select * from table limit offset,rows来实现。这里的offset是记录偏移量,它的计算方法是offset=$pagesize*($page-1),rows是要显示的记录条数,这里就是$page。也就是说select * from table limit 10,10这条语句的意思是取出表里从第11条记录开始的20条记录。

  二、主要代码解析

$pagesize=10; //设置每一页显示的记录数
$conn=mysql_connect("localhost","root",""); //连接数据库
$rs=mysql_query("select count(*) from tb_product",$conn); //取得记录总数$rs
$myrow = mysql_fetch_array($rs);
$numrows=$myrow[0];

//计算总页数

$pages=intval($numrows/$pagesize);

//判断页数设置

if (isset($_GET['page'])){
 $page=intval($_GET['page']);
}
else{
 $page=1; //否则,设置为第一页
}


  三、创建用例用表myTable

create table myTable(id int NOT NULL auto_increment,news_title varchar(50),news_cont text,add_time datetime,PRIMARY KEY(id))


  四、完整代码

<html>
<head>
<title>php分页示例</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<?php
 $conn=mysql_connect("localhost","root","");
 //设定每一页显示的记录数
 $pagesize=1;
 mysql_select_db("mydata",$conn);
 //取得记录总数$rs,计算总页数用
 $rs=mysql_query("select count(*) from tb_product",$conn);
 $myrow = mysql_fetch_array($rs);
 $numrows=$myrow[0];
 //计算总页数

 $pages=intval($numrows/$pagesize);
 if ($numrows%$pagesize)
  $pages ;
 //设置页数
 if (isset($_GET['page'])){
  $page=intval($_GET['page']);
 }
 else{
  //设置为第一页
  $page=1;
 }
 //计算记录偏移量
 $offset=$pagesize*($page - 1);
 //读取指定记录数
 $rs=mysql_query("select * from myTable order by id desc limit $offset,$pagesize",$conn);
 if ($myrow = mysql_fetch_array($rs))
 {
  $i=0;
  ?>
  <table border="0" width="80%">
  <tr>
   <td width="50%" bgcolor="#E0E0E0">
    <p align="center">标题</td>
    <td width="50%" bgcolor="#E0E0E0">
    <p align="center">发布时间</td>
  </tr>
  <?php
   do {
    $i ;
    ?>
  <tr>
   <td width="50%"><?=$myrow["news_title"]?></td>
   <td width="50%"><?=$myrow["news_cont"]?></td>
  </tr>
   <?php
   }
   while ($myrow = mysql_fetch_array($rs));
    echo "</table>";
  }
  echo "<div align='center'>共有".$pages."页(".$page."/".$pages.")";
  for ($i=1;$i< $page;$i )
   echo "<a href='fenye.php?page=".$i."'>[".$i ."]</a> ";
   echo "[".$page."]";
   for ($i=$page 1;$i<=$pages;$i )
    echo "<a href='fenye.php?page=".$i."'>[".$i ."]</a> ";
    echo "</div>";
   ?>
  </body>
  </html>


  五、总结

  本例代码在windows2000 server php4.4.0 mysql5.0.16上运行正常。该示例显示的分页格式是[1][2][3]…这样形式。假如想显示成“首页 上一页 下一页 尾页”这样形式,请加入以下代码:

$first=1;
$prev=$page-1;
$next=$page 1;
$last=$pages;

if ($page > 1)
{
 echo "<a href='fenye.php?page=".$first."'>首页</a> ";
 echo "<a href='fenye.php?page=".$prev."'>上一页</a> ";
}

if ($page < $pages)
{
 echo "<a href='fenye.php?page=".$next."'>下一页</a>
 echo "<a href='fenye.php?page=".$last."'>尾页</a> ";
}


  其实,写分页显示代码是很简单的,只要掌握了它的工作原理。希望这篇文章能够带给那些需要这方面程序web程序员的帮助。
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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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)

Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Mar 12, 2024 pm 07:20 PM

Pinduoduo software provides a lot of good products, you can buy them anytime and anywhere, and the quality of each product is strictly controlled, every product is genuine, and there are many preferential shopping discounts, allowing everyone to shop online Simply can not stop. Enter your mobile phone number to log in online, add multiple delivery addresses and contact information online, and check the latest logistics trends at any time. Product sections of different categories are open, search and swipe up and down to purchase and place orders, and experience convenience without leaving home. With the online shopping service, you can also view all purchase records, including the goods you have purchased, and receive dozens of shopping red envelopes and coupons for free. Now the editor has provided Pinduoduo users with a detailed online way to view purchased product records. method. 1. Open your phone and click on the Pinduoduo icon.

Reasons and solutions for desktop layout being locked Reasons and solutions for desktop layout being locked Feb 19, 2024 pm 06:08 PM

What happens when the desktop layout is locked? When using the computer, sometimes we may encounter the situation where the desktop layout is locked. This problem means that we cannot freely adjust the position of desktop icons or change the desktop background. So, what exactly is going on when it says that the desktop layout is locked? 1. Understand the desktop layout and locking functions. First, we need to understand the two concepts of desktop layout and desktop locking. Desktop layout refers to the arrangement of various elements on the desktop, including shortcuts, folders, widgets, etc. we can be free

Five selected Go language open source projects to take you to explore the technology world Five selected Go language open source projects to take you to explore the technology world Jan 30, 2024 am 09:08 AM

In today's era of rapid technological development, programming languages ​​are springing up like mushrooms after a rain. One of the languages ​​that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

How to display the wifi password QR code? It is recommended to scan the wifi password on WeChat in 3 seconds. How to display the wifi password QR code? It is recommended to scan the wifi password on WeChat in 3 seconds. Feb 20, 2024 pm 01:42 PM

You don’t need to enter the WIFI password often, so it’s normal to forget it. Today I will teach you the simplest way to find the password of your own WIFI. It can be done in 3 seconds. To check the WIFI password, use WeChat to scan it. The premise of this method is: there must be a mobile phone that can connect to WIFI. Okay, let’s start the tutorial: Step 1. We enter the phone, pull down from the top of the phone, bring up the status bar, and the WIFI icon. Step 2. Long press the WIFI icon to enter the WLAN settings; long press the WIFI icon. Step 3. Click Connected. Enter the WIFI name of your home, click Share Password, and a QR code will pop up; Step 4 of sharing WIFI password, we take a screenshot and save this QR code; Step 5, long press the WeChat icon on the desktop, and click Scan

How to check the current directory in Linux? How to check the current directory in Linux? Feb 23, 2024 pm 05:54 PM

In Linux systems, you can use the pwd command to display the current path. The pwd command is the abbreviation of PrintWorkingDirectory and is used to display the path of the current working directory. Enter the following command in the terminal to display the current path: pwd After executing this command, the terminal will display the full path of the current working directory, such as: /home/user/Documents. In addition, you can use some other options to enhance the functionality of the pwd command. For example, the -P option can display

Go language development essentials: 5 popular framework recommendations Go language development essentials: 5 popular framework recommendations Mar 24, 2024 pm 01:15 PM

"Go Language Development Essentials: 5 Popular Framework Recommendations" As a fast and efficient programming language, Go language is favored by more and more developers. In order to improve development efficiency and optimize code structure, many developers choose to use frameworks to quickly build applications. In the world of Go language, there are many excellent frameworks to choose from. This article will introduce 5 popular Go language frameworks and provide specific code examples to help readers better understand and use these frameworks. 1.GinGin is a lightweight web framework with fast

Samsung will provide displays for Microsoft's MR headsets, and the devices are expected to be lighter and have clearer displays Samsung will provide displays for Microsoft's MR headsets, and the devices are expected to be lighter and have clearer displays Aug 10, 2024 pm 09:45 PM

Recently, Samsung Display and Microsoft signed an important cooperation agreement. According to the agreement, Samsung Display will develop and supply hundreds of thousands of OLEDoS panels for mixed reality (MR) head-mounted devices to Microsoft. Microsoft is developing an MR device for multimedia content such as games and movies. This device is expected to It will be launched after the OLEDoS specifications are finalized, mainly serving the commercial field, and is expected to be delivered as early as 2026. OLEDoS (OLED on Silicon) technology OLEDoS is a new display technology that deposits OLED on a silicon substrate. Compared with traditional glass substrates, it is thinner and has higher pixels. OLEDoS display and ordinary display

See all articles