Home  >  Article  >  PHP Framework  >  How to implement paging in thinkphp

How to implement paging in thinkphp

PHPz
PHPzOriginal
2023-04-11 10:42:561894browse

ThinkPHP is a PHP framework based on the MVC development model. Since we are developing MVC applications, the paging function is indispensable. So, how does ThinkPHP implement paging? Let me introduce to you how ThinkPHP implements paging.

1. The basic concept of ThinkPHP paging

Paging is to divide a large data collection into N pages, so that users can only view part of them. There are two types of paging in ThinkPHP, one is normal paging and the other is AJAX paging.

Ordinary paging means that each page needs to refresh the entire page. The data is obtained from the server through PHP code and then returned to the client. This method of data interaction is inefficient, but it is simple to write.

AJAX paging is to request data asynchronously through the front-end, and transfer the data to the server through Ajax technology. After the server-side obtains the data from the database, it returns the data to the front-end. This method of data interaction is highly efficient, but requires the use of more complex front-end technology.

2. How to use paging in ThinkPHP

Specifically, the use of paging in ThinkPHP mainly includes two modules: Model module and View module. In the Model module, we query data from the database by using ThinkPHP's Query class or Db class. In the View module, we perform data display operations by using ThinkPHP's paging class Pagination and the built-in Paginator control.

  1. Implement data query operations in the Model module

In the Model module, we first need to query the data from the database, and then set the data according to the paging size Query offset and query quantity to return only the required page of data. The specific operations are as follows:

<?php
namespace Home\Model;
use Think\Model;
class UserModel extends Model{
    public function getPageUsers($page=1,$rows=10){
        $result = array();
        $count = $this->count(); // 获取总记录数
        $offset = ($page-1)*$rows; // 查询的起始位置
        $data = $this->limit($offset,$rows)->select(); // 查询当前页的记录
        $pagination = new \Think\Paginator($count,$rows); // 实例化分页对象
        $result['rows'] = $data;
        $result['pagination'] = $pagination->show(); // 获取分页显示的HTML代码
        return $result;
    }
}

In the above code, the count() method is used to obtain the total number of records, the limit() method is used to obtain the records of the current page, and the Pagination class is used to instantiate the paging object. It is worth noting that the limit() method supports chain operations and can be used in conjunction with the where() method to implement more complex query operations.

  1. Implement data display operations in the View module

In the View module, we need to use ThinkPHP’s built-in Paginator control to display paging information, and use ThinkPHP’s paging class Pagination to generate pagination HTML code. The specific operations are as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户信息管理</title>
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">用户信息管理</div>
        <div class="panel-body">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>年龄</th>
                    <th>电话</th>
                    <th>邮箱</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach($users[&#39;rows&#39;] as $user):?>
                <tr>
                    <td><?php echo $user[&#39;id&#39;];?></td>
                    <td><?php echo $user[&#39;name&#39;];?></td>
                    <td><?php echo $user[&#39;age&#39;];?></td>
                    <td><?php echo $user[&#39;phone&#39;];?></td>
                    <td><?php echo $user[&#39;email&#39;];?></td>
                </tr>
                <?php endforeach;?>
                </tbody>
            </table>
            <nav aria-label="Page navigation">
                <?php echo $users[&#39;pagination&#39;];?>
            </nav>
        </div>
    </div>
</div>
</body>
</html>

In the above code, we mainly use the Paginator control and Pagination class. In the Paginator control, we can set the layout, style, etc. of the control. In the Pagination class, we called the show() method to obtain the pagination HTML code for use by the Paginator control. At the same time, in the foreach loop, we display the $rows array transferred from the Model layer to the table.

3. Frequently asked questions about ThinkPHP paging

  1. How to set the number of records displayed on each page?

In the getPageUsers method of the Model layer, we can set the default number of records per page, as follows:

public function getPageUsers($page=1,$rows=10){
    ...
}

Among them, $rows represents the default number of records per page, we can also Directly pass parameters in the View layer to change the number of records per page.

  1. How to display the first page?

In the View layer, when the user clicks on the first page, the value of the $page parameter is 1, and we need to change the query range of the data accordingly. The specific operation is as follows:

public function getPageUsers($page=1,$rows=10){
    $result = array();
    $count = $this->count(); // 获取总记录数
    $offset = ($page-1)*$rows; // 查询的起始位置
    $data = $this->limit($offset,$rows)->select(); // 查询当前页的记录
    
    // 如果是第一页,直接返回第一页的数据
    if($page == 1){
        $pagination = new \Think\Paginator($count,$rows);
        $result['rows'] = $data;
        $result['pagination'] = $pagination->show();
        return $result;
    }
    
    // 如果不是第一页,则查询第一页的数据,获取分页HTML代码
    $firstPageData = $this->limit(0,$rows)->select();
    $pagination = new \Think\Paginator($count,$rows);
    $result['rows'] = $data;
    $result['pagination'] = str_replace("1</a>",$firstPageData."</a>",$pagination->show());
    return $result;
}

In the above code, when $page equals 1, we directly return the data of the first page. When $page is greater than 1, we re-query the first page data, obtain the paging HTML code, and replace it into the "first page" of the current page. In this way, you can click the "First Page" button on any page to return to the first page of data.

  1. How to use AJAX paging?

For ordinary paging, the entire page needs to be re-requested every time the page is turned, which is obviously inefficient for large data sets, so we often use AJAX technology to achieve refresh-free paging.

You need to pay attention to the following points when using AJAX paging:

(1) In the View layer, you need to add jQuery code similar to the above to monitor the paging button:

$(function () { // 加载页面时,注册分页事件
    $("#page").on('click','a',function(){
        var url = $(this).attr('href');
        $("#table").load(url);
        return false;
    });
});

In the above code, we add a click event listener to the paging button. When the button is clicked, an AJAX request is sent to fill the data back into the corresponding position.

(2) In the Model layer, JSON format data needs to be returned in the getPageUsers method, as follows:

public function getPageUsers($page=1,$rows=10){
    ...
    $result = array();
    $pagination = new \Think\Paginator($count,$rows);
    $result['rows'] = $data;
    $result['pagination'] = $pagination->show();
    return json_encode($result);
}

The json_encode() function is used here to format the data and return it in JSON format. . In this way, data can be easily parsed in the View layer.

The above is the detailed content of How to implement paging in thinkphp. 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