不管是官網還是網路上的分頁教學,你都無法使用嗎??
OK,讓我們一步一步來吧!
為了學習起見,這邊我略過model跟view層,直接在controller內做完。
CodeIgniter_3.0.0\application\controllers\Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index2() {
$fitle_ary=array('status' => '1');
$query = $this->db->get_where('news', $fitle_ary );//
$num_rows=$query->num_rows();//計算總數
$page=(int)$this->uri->segment(3); // 獲取頁碼
$page=($page=='')?1:$page;
$config['base_url'] = site_url(strtolower(__CLASS__).'/'.__FUNCTION__); //url地址
$config['total_rows'] = $num_rows;
$config['per_page'] = 3; //每頁幾筆
$config['use_page_numbers'] = TRUE; //使用頁碼方式而非偏移量傳值
$offset = $page == false?1:($config['per_page'] * ($page - 1)); // 用頁碼計算偏移量
$query = $this->db->get_where('news', $fitle_ary , $config['per_page'] , $offset);//
foreach ($query->result() as $row) {
echo $row->cont . '<br/>';
}
$this->load->library('pagination');
echo $this->pagination->initialize($config)->create_links();
}
}
MYSQL資料表內容
CREATE TABLE `news` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` varchar(200) NOT NULL,
`cont` text NOT NULL,
`status` tinyint(1) NOT NULL
) ENGINE='MyISAM';
-- ----------------------------
-- Records of news
-- ----------------------------
INSERT INTO "news" VALUES (1, 'gerg', 'sdvsdvdv', 1);
INSERT INTO "news" VALUES (2, 'dfbfdbdfb', 'dsbdsbdb', 1);
INSERT INTO "news" VALUES (3, 'dfbdf', 'sdbdsbsdb', 1);
INSERT INTO "news" VALUES (4, 'dfbdfb', 'sdvdsvdvsdv', 1);
INSERT INTO "news" VALUES (5, 'rgerg', 'erhff', 1);
INSERT INTO "news" VALUES (6, 'mhm', 'rehhrhrherhfdfndn ', 1);
接下來打開網址:
http://localhost/CodeIgniter_3.0.0/welcome/index2
看到了嗎??
漂亮的分頁效果,你已經完成。
分頁效果展示(第1頁) http://localhost/CodeIgniter_3.0.0/welcome/index2 |
sdvsdvdv dsbdsbdb sdbdsbsdb 12> |
分頁效果展示(第2頁) http://localhost/CodeIgniter_3.0.0/welcome/index2/2 |
sdvdsvdvsdv erhff rehhrhrherhfdfndn <12 |