CI框架分頁類及其實現
阿新 • • 發佈:2018-12-21
不BB了,直接上程式碼
Model類
class Page_model extends CI_Model
{
public function get_page()
{
//這是一個sql語句,查詢需要的結果,並將結果返回
$data = $this->db->select('id,name,age')->from('user')->get()->result_array();
return $data;
}
}
控制器類
class Pages extends CI_Controller { public function page(){ //載入分頁類 $this->load->library('pagination'); $perPage=10;//每頁10條 //配置項設定 $config['base_url']=site_url("pages/page"); $config['total_rows']=$this->db->count_all_results('user'); $config['per_page']=$perPage; $config['uri_segment']=3;//偏移量,預設是3,如果在控制器有二級目錄,根據偏移量層級而定 //自定義配置 $config['first_link']="首頁"; $config['prev_link']="上一頁"; $config['next_link']="下一頁"; $config['last_link']="尾頁"; //傳入配置項,並生成連結 $this->pagination->initialize($config); $data['links']=$this->pagination->create_links(); //設定偏移量 $offset=$this->uri->segment(3); $this->db->limit($perPage,$offset); //載入模型類和檢視 $this->load->model("page_model","page"); $data['user']=$this->page->get_page(); $this->load->view("pages/page.html",$data); } }
View檔案(page.html中的核心程式碼)
<table> <tr> <td>ID</td> <td>名字</td> <td>年齡</td> </tr> <?php foreach($user as $v):?> <tr> <td><?php echo $v['id'] ?></td> <td><?php echo $v['name'] ?></td> <td><?php echo $v['age'] ?></td> </tr> <?php endforeach?> </table> <?php echo $links ?>
效果圖