用户
 找回密码
 入住 CI 中国社区
搜索
查看: 5471|回复: 6
收起左侧

[讨论/交流] CI做分页类无法获取第一页

[复制链接]
发表于 2011-9-27 14:11:13 | 显示全部楼层 |阅读模式
本帖最后由 haoren26 于 2011-9-27 14:23 编辑

CI version:2.0.3
Environment:WAMP 2.1

看一哈子第三部视频,讲分页,我已经把全部的代码都写好了,但测试的时候发现点击一个分类的连接(比如“IT学习”),URI为http://localhost/admin/index.php/home/category/1,无法获得文章列表,错误如下:
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
SELECT * FROM article WHERE category_id = 1 ORDER BY id DESC LIMIT ,1

我在控制器home.php里是这样写的
home.php
PHP复制代码
 
function category()
        {
        $this->load->model('Mhome');
        $data['category'] = $this->Mhome->get_category();
        $data['get_category_name'] = $this->Mhome->get_category_name($this->uri->segment(3));
        $data['page_title']='CI开发新闻发布体系';
        $this->load->view('header_view',$data);
        $config['base_url'] = base_url().'index.php/home/category/'.$this->uri->segment(3);
        $config['total_rows'] = $this->Mhome->select_num_rows($this->uri->segment(3));
        $config['per_page'] = 1;
        $config['uri_segment'] = 4;   //问题出在这里!!
        $this->pagination->initialize($config);
        $data['article_list'] = $this->Mhome->get_page($this->uri->segment(3),$this->uri->segment(4),$config['per_page']);
        $this->load->view('category_view',$data);
        $this->load->view('footer_view');
        }
 
复制代码

get_page方法写在模型Mhome.php里
Mhome.php
PHP复制代码
 
function get_page($category_id,$offset,$num) //分页
{
 
       $sql = "SELECT * FROM article WHERE category_id = $category_id ORDER BY id DESC LIMIT $offset,$num";
       $query = $this->db->query($sql);
       return $query->result();
 }
 
复制代码


如果我在地址栏输入 http://localhost/admin/index.php/home/category/1/1,则可以访问第二页的内容,因为它有第四个URI节段,但第一页的URI就是 http://localhost/admin/index.php/home/category/1,它没有第四个节段,于是就无法获取文章列表,这让我苦恼,该怎么能显示第一页呢?
发表于 2011-9-27 15:18:30 | 显示全部楼层
你要给 $offset 一个默认值 0。
建议使用 AR 来写 SQL 语句。
发表于 2011-9-28 11:13:22 | 显示全部楼层
本帖最后由 leanhunter 于 2011-9-28 11:15 编辑

你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认值我这里写的1
$data['article_list'] = $this->Mhome->get_page($this->uri->segment(3),$this->uri->segment(4) ? $this->uri->segment(4) : 1,$config['per_page']);


CI的错误提示真不错。
 楼主| 发表于 2011-9-28 22:28:20 | 显示全部楼层
本帖最后由 haoren26 于 2011-9-28 22:28 编辑
leanhunter 发表于 2011-9-28 11:13
你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认 ...


新手,不知道默认值怎么设置,呵呵。但是我看视频里没有设置默认值也能运行啊,视频里第一页只有三个URI节段。。。不过视频里的CI版本是1.7的

默认值的设置格式就是你这样子吗?
发表于 2011-9-29 10:50:21 | 显示全部楼层
学到了  
 楼主| 发表于 2011-9-29 23:17:15 | 显示全部楼层
leanhunter 发表于 2011-9-28 11:13
你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认 ...

你的做法可行!谢谢!请问这是PHP函数传默认值的方法吗?

我后来发现还有一种方法,就是$this->uri->segment(4,0),第二个参数就是当无法得到返回值时返回一个默认值。一哈子的视频里就是这样子做的,是我没仔细看呵呵
发表于 2015-3-7 17:43:45 | 显示全部楼层
leanhunter 发表于 2011-9-28 11:13
你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认 ...

$this->uri->segment(4,1);可以直接这样赋默认值

本版积分规则