Heim  >  Artikel  >  Backend-Entwicklung  >  CodeIgniter(CI 3.0)分页类实践记录

CodeIgniter(CI 3.0)分页类实践记录

WBOY
WBOYOriginal
2016-06-23 13:19:00848Durchsuche

最近在学习B/S,选择了PHP CI框架作为切入点。

在尝试制作个人CMS的时候遇到了需要分页的情况,网上好像搜不到3.0版本以上的例子,下面附上本地实验的代码,供参考。

数据库情况如下:

首先看Controller

<?php/** * Created by PhpStorm. * User: erdao * Date: 16-1-11 * Time: 下午10:25 */class P extends CI_Controller{    /**     * P constructor.     */    public function __construct()    {        parent::__construct();        $this->load->model('article_model','article');        $this->load->library('pagination');    }    /**     * @param int $page 可看做offset     */    public function index($page=0)    {        //每页显示三条数据        $limit['num']=3;        $limit['offset']=$page;        $config['base_url']=site_url('p/index');        $config['total_rows']=$this->article->get_articles_num();//数据总条数        $config['per_page']=$limit['num'];//每页显示条数        $this->pagination->initialize($config);        $data=array(            'articles'=>$this->article->get_limit_articles($limit)        );        $this->load->view('page_ex',$data);    }}

再来Model

<?php/** * Created by PhpStorm. * User: erdao * Date: 16-1-12 * Time: 下午9:48 */class Article_model extends CI_Model{    /**     * Article_model constructor.     */    public function __construct()    {        parent::__construct();    }    /**     * 获取全部数据     * @return mixed     */    public function get_all_articles()    {        $this->db->from('my_article');        $this->db->order_by('posttime', 'DESC');        $query=$this->db->get();        return $query->result_array();    }    /**     * 获取表内数据数量     * @return mixed     */    public function get_articles_num()    {        return $this->db->count_all('my_article');    }    /**     * 获取有限个数的数据     * @param array $arr     * @return mixed     */    public function get_limit_articles($arr=array('num'=>FALSE,'offset'=>FALSE))    {        if(isset($arr['num']) and isset($arr['offset']) and ($arr['num']!==FALSE) and ($arr['offset']!==FALSE))        {            $query=$this->db->get('my_article',$arr['num'],$arr['offset']);            return $query->result_array();        }        else        {            return $this->get_all_articles();        }    }}

最后是view

<?phpforeach($articles as $item){    echo $item['title'];}echo $this->pagination->create_links();

附上运行效果截图

需要注意的是,index/9 这里面的9可以看做是数据库中的索引(index),而不是页数

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn