search
HomePHP FrameworkThinkPHPImplementation and precautions of paging page number jump function in ThinkPHP3.2

With the continuous development of modern Internet technology, the number of website visits is increasing. In order to facilitate users to access data, the paging function has become one of the essential functions of modern websites. In the ThinkPHP3.2 framework, the paging function is also very flexible, and you can customize the paging style and page number jump function. This article will introduce the implementation method and precautions of the paging page number jump function in ThinkPHP3.2.

1. Paging function of ThinkPHP3.2

In the ThinkPHP3.2 framework, simple paging function can be implemented through the following methods:

// 查询数据
$list = M('User')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

// 实例化分页类
$Page = new \Think\Page($count,$pageSize);

// 输出分页html
$this->assign('page',$Page->show());

Among them, $list is the query For the data obtained, $where is the query condition, $count is the total number of query data, and $pageSize is the amount of data displayed on each page. After instantiating the \Think\Page class, you can output paginated html through the $Page->show() method.

2. Customized paging style

In the ThinkPHP3.2 framework, you can customize the paging style through the following methods:

  1. Define paging style

Create a file named Page.class.php in the current project and copy the following code into the file:

<?php namespace Think;
class Page {
    // 定义分页样式
    private $rollPage   = 5; // 分页栏每页显示的页数
    private $lastSuffix = true; // 是否显示最后一页的页码后缀
    private $config     = array(
        &#39;header&#39; => '<span>共 %TOTAL_ROW% 条记录</span>',
        'prev'   => ' '>>',
        'first'  => '1...',
        'last'   => '...%TOTAL_PAGE%',
        'theme'  => '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%',
    );
    private $totalRows  = 0; // 总行数
    private $listRows   = 20; // 每页显示行数
    private $totalPages = 0; // 总页数
    private $nowPage    = 1; // 当前页数
    private $firstRow   = 1; // 起始行数
    private $varPage    = 'page'; // 分页变量名
    private $p          = 'p'; // 分页参数名
    private $url        = ''; // 当前链接URL
    private $baseUrl    = ''; // 分页基础URL
    private $params     = array(); // 分页跳转时要带的参数
    private $anchor     = ''; // 锚点参数
    // 构造方法
    public function __construct($totalRows,$listRows='',$p='page'){
        $this->totalRows = $totalRows;
        $this->varPage = $p;
        if (!empty($listRows)) {
            $this->listRows = $listRows;
        }
        $this->totalPages = ceil($this->totalRows/$this->listRows); //总页数
        $this->nowPage    = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
        if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
            $this->nowPage = $this->totalPages;
        }
        $this->firstRow   = $this->listRows*($this->nowPage-1);
    }
    // 显示分页
    public function show($url='') {
        if (0 == $this->totalRows) {
            return '';
        }

        // 记录当前URL
        $this->url = empty($url) ? U(ACTION_NAME).'/' : $url;
        // 获取当前页码
        $this->nowPage    = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
        // 计算分页信息
        $this->totalPages = ceil($this->totalRows/$this->listRows);

        // 分页处理
        if($this->totalPages > $this->rollPage){
            $linkPage = "
    ";             $inum = floor($this->rollPage/2);             if($this->nowPage lastSuffix=false;             }             if($this->nowPage > 1){                 $this->addUrl($linkPage,$this->nowPage-1,'上一页','class="prev"');             }             for($i = 1; $i rollPage; $i++){                 if(($this->nowPage+$inum) >= $this->totalPages && $this->totalPages > $this->rollPage){                     $page = $this->totalPages-$this->rollPage+$i;                 }else{                     $page = $this->nowPage-$inum+$i;                 }                 if($page > 0 && $page != $this->nowPage){                     if($page totalPages){                         $this->addUrl($linkPage,$page,'第'.$page.'页','');                     }else{                         break;                     }                 }else{                     if($page > 0 && $this->rollPage totalPages){                         $this->addUrl($linkPage,$page,'第'.$page.'页','');                     }                 }             }             if($this->nowPage totalPages){                 $this->addUrl($linkPage,$this->nowPage+1,'下一页','class="next"');             }             if($this->lastSuffix){                 $this->addUrl($linkPage,$this->totalPages,'最后一页');             }             $linkPage.='
';         }else{             $linkPage = "
    ";             for($i=1;$itotalPages;$i++){                 if($this->nowPage==$i) {                     $linkPage.='
  • '.$i.'
  • ';                 } else {                     $this->addUrl($linkPage,$i,'第'.$i.'页','');                 }             }             $linkPage.='
';         }         $pageStr  = str_replace(             array('%HEADER%','%NOW_PAGE%','%TOTAL_PAGE%','%TOTAL_ROW%','%FIRST%','%UP_PAGE%','%LINK_PAGE%','%DOWN_PAGE%','%END%'),             array($this->config['header'],$this->nowPage,$this->totalPages,$this->totalRows,$this->config['first'],$this->config['prev'],$linkPage,$this->config['next'],$this->config['last']),$this->config['theme']);         return $pageStr;     }     // 添加分页URL     protected function addUrl(&$linkPage,$page,$text,$class=''){         if($page > 0){             $url = $this->url;             $url .= strpos($url,'?') ? '&' : '?';             $url .= $this->p.'='.$page;             if(!empty($this->params)){                 foreach($this->params as $key=>$val){                     $url .= '&'.$key.'='.$val;                 }             }             if(!empty($this->anchor)){                 $url .= '#'.$this->anchor;             }             $linkPage.='
  • '.$text.'
  • ';         }     } }
    1. Use custom paging style

    Introduce a custom paging style into the controller and use it in the following way:

    // 引入分页类
    import("Think.Page");
    // 查询数据总数
    $count = M('User')->where($where)->count();
    // 实例化分页类
    $Page = new \Think\Page($count,$pageSize);
    // 自定义分页样式
    $Page->setConfig('prev', '上一页');
    $Page->setConfig('next', '下一页');
    $Page->setConfig('first', '第一页');
    $Page->setConfig('last', '最后一页');
    $Page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
    // 查询数据
    $list = M('User')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    // 输出分页html
    $this->assign('page',$Page->show());

    3. Pagination page number jump function

    In the ThinkPHP3.2 framework, the paging page number jumps The transfer function is implemented by adding input boxes and buttons in the paging style. The steps to add the page number jump function are as follows:

    1. Modify the paging style

    Add an input box and a button in the custom paging style:

    $Page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% <div>
    <input><span><button>GO!</button></span>
    </div>');
    1. Use the paging page jump function

    In the view file, you can directly use the customized paging style and implement the page jump function:

    <div>
        <?php  echo $page;?>
    </div>

    Among them, in In the custom paging style, use "__PAGE__" and "__HREF__" to represent the current page number and jump link respectively. Enter the jump page number in the input box and click the button to jump to the page number.

    Summary

    In the ThinkPHP3.2 framework, the paging page number jump function can be implemented by adding input boxes and buttons in the paging style. Using custom paging styles can make the paging style more beautiful, and can also achieve more specific paging needs.

    The above is the detailed content of Implementation and precautions of paging page number jump function in ThinkPHP3.2. For more information, please follow other related articles on the PHP Chinese website!

    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
    What is the difference between think book and thinkpadWhat is the difference between think book and thinkpadMar 06, 2025 pm 02:16 PM

    This article compares Lenovo's ThinkBook and ThinkPad laptop lines. ThinkPads prioritize durability and performance for professionals, while ThinkBooks offer a stylish, affordable option for everyday use. The key differences lie in build quality, p

    How to prevent SQL injection tutorialHow to prevent SQL injection tutorialMar 06, 2025 pm 02:10 PM

    This article explains how to prevent SQL injection in ThinkPHP applications. It emphasizes using parameterized queries via ThinkPHP's query builder, avoiding direct SQL concatenation, and implementing robust input validation & sanitization. Ad

    How to deal with thinkphp vulnerability? How to deal with thinkphp vulnerabilityHow to deal with thinkphp vulnerability? How to deal with thinkphp vulnerabilityMar 06, 2025 pm 02:08 PM

    This article addresses ThinkPHP vulnerabilities, emphasizing patching, prevention, and monitoring. It details handling specific vulnerabilities via updates, security patches, and code remediation. Proactive measures like secure configuration, input

    How to fix thinkphp vulnerability How to deal with thinkphp vulnerabilityHow to fix thinkphp vulnerability How to deal with thinkphp vulnerabilityMar 06, 2025 pm 02:04 PM

    This tutorial addresses common ThinkPHP vulnerabilities. It emphasizes regular updates, security scanners (RIPS, SonarQube, Snyk), manual code review, and penetration testing for identification and remediation. Preventative measures include secure

    How to install the software developed by thinkphp How to install the tutorialHow to install the software developed by thinkphp How to install the tutorialMar 06, 2025 pm 02:09 PM

    This article details ThinkPHP software installation, covering steps like downloading, extraction, database configuration, and permission verification. It addresses system requirements (PHP version, web server, database, extensions), common installat

    Detailed steps for how to connect to the database by thinkphpDetailed steps for how to connect to the database by thinkphpMar 06, 2025 pm 02:06 PM

    This guide details database connection in ThinkPHP, focusing on configuration via database.php. It uses PDO and allows for ORM or direct SQL interaction. The guide covers troubleshooting common connection errors, managing multiple connections, en

    How can I use ThinkPHP to build command-line applications?How can I use ThinkPHP to build command-line applications?Mar 12, 2025 pm 05:48 PM

    This article demonstrates building command-line applications (CLIs) using ThinkPHP's CLI capabilities. It emphasizes best practices like modular design, dependency injection, and robust error handling, while highlighting common pitfalls such as insu

    How to use thinkphp tutorialHow to use thinkphp tutorialMar 06, 2025 pm 02:11 PM

    This article introduces ThinkPHP, a free, open-source PHP framework. It details ThinkPHP's MVC architecture, features (routing, database interaction), advantages (rapid development, ease of use), and disadvantages (potential over-engineering, commun

    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

    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

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment