class User extends CI_Controller{
//构造函数
function __construct()
{
parent::__construct();
//载入用户模型
$this->load->model("User_model");
$this->load->helper('url');
header("content-type:text/html;charset=utf-8");
// mysql_query("set names gbk");
}
//显示用户信息列表
public function index()
{ //调用用户模型中的get方法,将结果集返回给$query
$this->load->library('pagination'); //导入分页类
$config['base_url'] = base_url().'index.php/user/index/'; //导入分页类URL(就是要实现分页的那个模板页的路径)
$total_rows=$this->User_model->cha();
$config['total_rows'] = $total_rows; //计算总记录数
$config['per_page'] = '2'; //每页显示的记录数
$config['cur_tag_open'] = '[';
//“当前页”链接的打开标签。
$config['cur_tag_close'] = ']';
//“当前页”链接的关闭标签。
$config['full_tag_open'] = '';
$config['full_tag_close'] = '';
//将结果集作为关联数组返回
$data['url'] = base_url();
$this->pagination->initialize($config); //初始化分类页
$list=$this->User_model->cha($config['per_page'],$this->uri->segment(3));//每一页的内容
$data['userList']=$list->result_array();
$data['page']=$this->pagination->create_links();
$this->load->view('user/user',$data);
}
4model 里的代码
public function cha($num=0,$offset=0)
{
$data = '';
//SQL语句的select部分,这里查询user表的所有字段
$this->db->select("u.id,u.name,u.nickname,i.b_thumb");
$this->db->from("user as u");
$this->db->join("img as i",'u.id=i.pid');
$this->db->order_by("u.id asc");
//运行选择查询语句并且返回结果集给$data
if($num||$offset)
{
$data=$this->db->get('',$num,$offset);
return $data;
}else{
$data=$this->db->get('');
$total_num=$data->num_rows();
return $total_num;
}
}
5视图里的代码
6 中间 疑惑的地方
开始 的echo base_url();结果报错。sol:构造函数内用helper $this->load->helper('url');
给当前页加区别:
$config['cur_tag_open'] = '[';
//“当前页”链接的打开标签。
$config['cur_tag_close'] = ']';
$data['url'] = base_url();
//这里 我开始写的是: $data['url']=$config['url'];
结果图片显示不出来 我才发现这个路径多了index.php 所以改成 这个。
$this->pagination->initialize($config); //初始化分类页
把上面的$config[] 属性 填充之后 用$this->pagination->initialize();来初始化
$list=$this->User_model->cha($config['per_page'],$this->uri->segment(3));//每一页的内容
$this->uri>segment(3) 的东西我看了下手册 是说 是 后面的第三部分。
例如:http://localhost/ci/index.php/user/index/3
我自己的理解 就是 从index.php后的类名 ,方法名,参数
参数就是 所谓的 segment(3)吧
segments
- n. 片段;段数(segment的复数);积弓形片模型
- v. 把…分割成段;细胞分裂(segment的三单形式)
把cha()的方法 要用$list->result_array();
转化为数组 不然 什么都查不到
这里 你把查询的结果集 赋值为什么 $list 就替换成什么。
$a=你的结果集
$a->result_array();
$data['page']=$this->pagination->create_links();
用这个方法 就像 把分页的赋值为$data['page']
在模板里 直接 echo $page 就好了。