Home Backend Development PHP Tutorial Detailed explanation of the process of turning the previous page to the next page in php

Detailed explanation of the process of turning the previous page to the next page in php

Aug 01, 2020 pm 04:36 PM
php Web page

Detailed explanation of the process of turning the previous page to the next page in php

前言

这几天做项目因为数据太多,需要对信息进行上下翻页展示,就自己写了翻页的代码
大致功能就是页面只显示几条信息,按上一页、下一页切换内容,当显示第一页时上一页和首页选项不可选,当页面加载到最后一页时下一页和尾页选项不可选

具体效果如下:

相关学习推荐:PHP编程从入门到精通

实现代码

1)原生PHP方法

先说一下总思路吧,首先我们要查询所有符合条件需要进行分页的总数据,计算展示的总页数。

然后获取当前显示的是第几页信息,用当前页数每页数据条数表示为总数据的第几条,再根据限制条件查询出当前页所需显示出来的数据。将每一条数据echo替换HTML结构内容中,最后显示出来

关于分页的限制条件很简单,只要查询到当前页为第1页时,首页和上一页选项跳转链接都固定在第一页同时设置选项disabled不可选,尾页也是相同的步骤。

具体代码如下:

当前页cPage需要传过来,我的办法是初始cPage=0

list.php*

<a href="listmore.php?cPage=0" rel="external nofollow" rel="external nofollow" class="pull-right">更多&gt;&gt;</a>
$row=$table->fetch()每次读取一条信息,得到的是一个索引数组,代码里的$row[&#39;id&#39;]表示$row里面名为id的值,也可表示为$row.id
Copy after login

connect.php(连接数据库)

<?php
$link=new PDO("mysql:host=localhost;port=3306;dbname=db","root","");
$link->query("set names utf8");
Copy after login
Copy after login

listmore.php

 <ul id="list" class="media-list">
  <?php
    include_once(&#39;connect.php&#39;);
    $result = $link->query("select * from news");
    $total=$result->rowCount();//查询出来符合条件的总数
    $pages=ceil($total/4);//分页的总页数  
    $num = 4;//每页显示的数据条数
    $cPage = $_GET[&#39;cPage&#39;];//获取当前是显示的第几页
    $start = $cPage * $num;//第一条数据
    $table = $link->query("select * from news order by id desc limit {$start},$num");
    $link = null;//销毁
    while ($row=$table->fetch()){//每次读出一条数据,赋给$row
      //插入多行文本,把值替换掉
    echo <<<_
      <li class="media">
        <a href="detail.php?id={$row[&#39;id&#39;]}">
        <img class="pull-left" src="{$row[&#39;src&#39;]}">
        <figcaption>
        <h4><span class="title">{$row[&#39;title&#39;]}</span> <span class="news-date">{$row[&#39;time&#39;]}</span></h4>
        <p>{$row[&#39;content&#39;]}</p>
        </figcaption>
        </a>
      </li>
  _;
    }
  ?>
</ul>
Copy after login

上下翻页:

<p class="page text-center">
 <ul class="pagination" id="page">
  <li data-i="0" id="index" class="<?php if ($cPage==0) echo &#39;disabled&#39;; ?>"><a href="listmore.php?cPage=0">&laquo;首页</a></li>
  <li data-i="1" class="<?php if ($cPage==0) echo &#39;disabled&#39;;?>"><a href="listmore.php?cPage=<?php echo $cPage>0?$cPage-1:0?>">&lt;上一页</a></li>
  <li data-i="2" class="<?php if ($cPage==$pages-1) echo &#39;disabled&#39;?>"><a href="listmore.php?cPage=<?php echo $cPage==($pages-1)?$pages-1:$cPage+1?>">下一页&gt;</a></li>
  <li data-i="3" id="end" class="<?php if ($cPage==$pages-1) echo &#39;disabled&#39;?>"><a href="listmore.php?cPage=<?php echo $pages-1?>">尾页&raquo;</a></li>
  <li class="disabled">
    <a href="##" id="total"><?php echo ($cPage+1)?>/<?php echo "$pages"?></a>
  </li>
  </ul>
</p>
Copy after login

2)ajax方法

HTML代码,展示信息装在panel-body里面

 <p class="panel-body" id="content">
    <ul id="list" class="media-list">  
     </ul>
  </p>
  <p class="page text-center">
     <ul class="pagination" id="page">
       <li data-i="0" id="index" class="disabled"><a href="##">&laquo;首页</a></li>
       <li data-i="1" class="disabled"><a href="##">&lt;上一页</a></li>
       <li data-i="2"><a href="##">下一页&gt;</a></li>
       <li data-i="3" id="end"><a href="##">尾页&raquo;</a></li>
       <li class="disabled">
         <a href="##" id="total"></a>
       </li>
     </ul>
   </p>
   <template id="temp">     //引用模板
    <li class="media">
      <a href="detail.html?id={id}">
        <img class="pull-left" src="{src}">
        <figcaption>
          <h4><span class="title">{title}</span> <span class="news-date">{date}</span></h4>
  
          <p>{content}</p>
         </figcaption>
        </a>
      </li>
    </template>
Copy after login

JS代码:

 var html=$(&#39;#temp&#39;).html();
  var curPage=0,pages=0;
  $.getJSON(&#39;php/pages.php&#39;,function (res) {
    pages=Math.ceil(res/4);/*获取信息的总页数*/
  });
  function show(cPage){//替换每一页的内容
    $.getJSON(&#39;php/listmore.php&#39;,{cPage:cPage},function (json) {
      var str=&#39;&#39;;
      $(&#39;#list&#39;).empty();
      json.forEach(function (el) {
        str+=html.replace(&#39;{id}&#39;,el.id).replace(&#39;{title}&#39;,el.title).replace(&#39;{src}&#39;,el.src)
          .replace(&#39;{content}&#39;,el.content).replace(&#39;{date}&#39;,el.time);
      });
      $(&#39;#list&#39;).html(str);
    });
    $(&#39;#total&#39;).html((curPage+1)+&#39;/&#39;+pages);
  }
  setTimeout(function () {
    show(0);
  },100);
  $(&#39;#page&#39;).on(&#39;click&#39;,&#39;li&#39;,function () {//上下翻页,翻遍当前页的值
    var i=$(this).data(&#39;i&#39;);//jquery里特有的获取data-*属性的方法
    switch (i){
      case 0:curPage=0;break;
      case 1:curPage>0?curPage--:0;break;
      case 2:curPage<(pages-1)?curPage++:pages-1;break;
      case 3:curPage=pages-1;break;
    }
    show(curPage);
    disabled(curPage);
  })
  function disabled(curPage) {//关于临界值禁止选择
    if (curPage==0){/*当前页为第一页,首页和上一页选项禁止点击*/
      $(&#39;#index&#39;).addClass(&#39;disabled&#39;).next().addClass(&#39;disabled&#39;);
      $(&#39;#end&#39;).removeClass(&#39;disabled&#39;).prev().removeClass(&#39;disabled&#39;);
    } else if (curPage==pages-1){
      $(&#39;#index&#39;).removeClass(&#39;disabled&#39;).next().removeClass(&#39;disabled&#39;);
      $(&#39;#end&#39;).addClass(&#39;disabled&#39;).prev().addClass(&#39;disabled&#39;);
    } else {/*当前页为最后一页,尾页和下一页选项禁止点击*/
      $(&#39;#index&#39;).removeClass(&#39;disabled&#39;).next().removeClass(&#39;disabled&#39;);
      $(&#39;#end&#39;).removeClass(&#39;disabled&#39;).prev().removeClass(&#39;disabled&#39;);
    }
  }
Copy after login

connect.php(连接数据库)

<?php
$link=new PDO("mysql:host=localhost;port=3306;dbname=db","root","");
$link->query("set names utf8");
Copy after login
Copy after login

pages.php(获取总页数)

<?php
include_once(&#39;connect.php&#39;);//连接数据库
$result = $link->query("select * from news");
$row=$result->rowCount();
echo $row;
Copy after login

listmore.php(获取数据库里的数据)

<?php
include_once (&#39;connect.php&#39;);
$num = 4;//每一页显示的数据条数
$cPage = $_GET[&#39;cPage&#39;];//获取当前页
$start = $cPage * $num;//计算当前页显示的第一条数据的数目
/*从表中查询从开始$start的一共$num条数据*/
$result = $link->query("select * from news order by id desc limit {$start},$num");
$link = null;
while ($row=$result->fetch()){/*每一次读取一条数据*/
$json[]=$row;/*把数据赋给json数组*/
}
echo json_encode($json);/*把json数组以json格式返回给HTML*/
Copy after login

The above is the detailed content of Detailed explanation of the process of turning the previous page to the next page in php. For more information, please follow other related articles on the PHP Chinese website!

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 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