haoren26 发表于 2011-9-27 14:11:13

CI做分页类无法获取第一页

本帖最后由 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

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

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,它没有第四个节段,于是就无法获取文章列表,这让我苦恼,该怎么能显示第一页呢?

Hex 发表于 2011-9-27 15:18:30

你要给 $offset 一个默认值 0。
建议使用 AR 来写 SQL 语句。

leanhunter 发表于 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的错误提示真不错。

haoren26 发表于 2011-9-28 22:28:20

本帖最后由 haoren26 于 2011-9-28 22:28 编辑

leanhunter 发表于 2011-9-28 11:13 static/image/common/back.gif
你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认 ...

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

默认值的设置格式就是你这样子吗?

NicholasWay 发表于 2011-9-29 10:50:21

学到了

haoren26 发表于 2011-9-29 23:17:15

leanhunter 发表于 2011-9-28 11:13 static/image/common/back.gif
你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认 ...

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

我后来发现还有一种方法,就是$this->uri->segment(4,0),第二个参数就是当无法得到返回值时返回一个默认值。一哈子的视频里就是这样子做的,是我没仔细看呵呵

meir_lia_seven 发表于 2015-3-7 17:43:45

leanhunter 发表于 2011-9-28 11:13
你得设置默认值呀姐姐。。。错误提示里面,你的Limit 后面有一个参数为空,这个肯定要自己处理的呀。

默认 ...

$this->uri->segment(4,1);可以直接这样赋默认值
页: [1]
查看完整版本: CI做分页类无法获取第一页