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

How to do paging in thinkphp

PHPz
PHPzOriginal
2023-04-11 09:13:56871browse

ThinkPHP is a PHP development framework based on MVC architecture. It provides convenient function modules and rich library functions, which facilitates the development of fast and simple Web applications. In ThinkPHP applications, data paging is a frequently used feature. Here's how to implement data paging in ThinkPHP.

1. Code implementation in the controller

In the controller method, we can implement the data paging function through the built-in paging class \think\paginator\driver\Bootstrap of the TP framework . We can first query the data to be paging, then pass the query results to the paging class, and then call the render() method of the paging class.

The following is an example of controller code:

use \think\paginator\driver\Bootstrap;

public function index()
{

// 查询文章列表数据
$articles = Db::name('article')->paginate(10);

// 将查询结果传递给分页类
$page = $articles->render();

// 将分页后的数据传递给模板
$this->assign('articles', $articles);
$this->assign('page', $page);

return $this->fetch('index');

}

In the sample code, parameter 10 in the paginate() method specifies the amount of data displayed on each page. The $articles variable stores the queried article list data, and the $page variable stores the paging HTML code.

2. Code implementation in the template

In the template, we can return the paging HTML code through the render() method of the paging class, and then render the paging navigation on the page.

The following is an example of template code:

    {volist name="articles" id="article"}
        <li>{$article.title}</li>
    {/volist}