Home  >  Article  >  Backend Development  >  Implementation of ThinkPHP paging_PHP tutorial

Implementation of ThinkPHP paging_PHP tutorial

WBOY
WBOYOriginal
2016-07-14 10:10:44786browse

分页类需要和查询相结合,我们可以使用ThinkPHP自带的limit方法或者page方法,目的就是为了获取当前分页的数据(也有先获取完整数据然后前端分页显示的方法,不在本文描述内容中,也不建议)。使用limit方法或者page方法是和数据库类型无关的。
我们首先在数据库里面创建一个think_datas数据表用于测试:

    CREATE TABLE IF NOT EXISTS `think_data` (
      `id` smallint(4) unsigned NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `content` varchar(255) NOT NULL,
      `create_time` int(11) unsigned NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ; 

 

 

  要使用分页查询,一般来说需要进行两次查询,即第一次查询得到满足条件的总数据量,然后第二次查询当前分页的数据,这样做的作用是告诉分页类当前的数据总数,以便计算生成的总页数(如果你的显示只是需要上下翻页的话,其实总数查询可以省略或者进行缓存)。
一个标准的分页使用示例如下:


    $Data = M('Data'); // 实例化Data数据对象

    import('ORG.Util.Page');// 导入分页类
    $count      = $Data->where($map)->count();// 查询满足要求的总记录数 $map表示查询条件
    $Page       = new Page($count);// 实例化分页类 传入总记录数
    $show       = $Page->show();// 分页显示输出
    // 进行分页数据查询
    $list = $Data->where($map)->order('create_time')->limit($Page->firstRow.','.$Page->listRows)->select();
    $this->assign('list',$list);// 赋值数据集
    $this->assign('page',$show);// 赋值分页输出

    $this->display(); // 输出模板

 

 

 

如果没有任何数据的话,分页显示为空白。所以在进行测试之前,请确保你的数据表里面有一定的数据,否则可能看不到分页的效果。如果使用page方法查询的话,则成:可以改

    $Data = M('Data'); // 实例化Data数据对象
    import('ORG.Util.Page');// 导入分页类
    $count      = $Data->where($map)->count();// 查询满足要求的总记录数
    $Page       = new Page($count);// 实例化分页类 传入总记录数
    // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
    $nowPage = isset($_GET['p'])?$_GET['p']:1;
    $list = $Data->where($map)->order('create_time')->page($nowPage.','.$Page->listRows)->select();
    $show       = $Page->show();// 分页显示输出
    $this->assign('page',$show);// 赋值分页输出
    $this->assign('list',$list);// 赋值数据集
    $this->display(); // 输出模板


然后,我们在模板中添加分页输出变量即可:

 








       

[ {$vo.create_time|date='Y-m-d H:i:s',###} ] {$vo.title}

{$page}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477453.htmlTechArticleThe paging class needs to be combined with the query. We can use the limit method or page method that comes with ThinkPHP. The purpose is to Get the data of the current page (you can also get the complete data first and then...
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