问题的来源(和错误的结果)是你混合访问数据库的方法有两种:
- 与查询()函数你有效地执行其作为通过SQL它的论点。这个函数返回一个需要被利用的Result对象。
- 与count_all_results()函数,你正在运行一个“SELECT COUNT(*)”(或东西等效)上的一个查询/选择标准[您之前必须建立的当前状态通过链接运营为像这样,* not_like *,从,其中等]。该函数返回一个整数,该整数是行数。
在问题片段的情况下,活动记录上下文在[query()调用之后)完全重置,并且由于您甚至不传递表名或其他条件,函数将返回值1(也许是因为结果是一个错误或某种'那样)。
因此,应该挑选一个或其他方法,即。具体而言,无论是:
// Note how we use COUNT(*) as suggested in other comments and answers, since
// we do not need the actual data, just the count
// If you are intent on the original, very inefficient approach, use the
// select * ... query and then get the number of rows with something like
// $count = $myResults->num_rows();
// Also, unrelated, note how the $data['id'] expression was removed from the
// string literal since it needs to be evaluated by PHP not by SQL (thanks
// to Nichola Peluchetti for pointing that out).
$sql = "select COUNT(*) AS NbOfRows FROM messages WHERE user_id = {".$data['id']."}
AND time > DATE_SUB(now(), INTERVAL 1 DAY)";
$myResults = $this->db->query($sql);
$count = $myResults->row()->NbOfRows
或
// build your search criteria
$this->db->from('messages');
$this->db->where('user_id', $data['id']);
$this->db->where('time >', 'DATE_SUB(now(), INTERVAL 1 DAY)')
// $this->db->where("'time >' DATE_SUB(now(), INTERVAL 1 DAY)")
$count = $this->db->count_all_results();
对于第2个办法,我不是100%如何/如果文字 'DATE_SUB()...' 有效地被传递和执行SQL(因为它是一个SQL函数,所以它是必须的),但这是另一个问题;为了安全起见,请使用注释掉的语法,该语法使用单个,其中表达式作为单个字符串传递。
这个答案的一点是,你需要为使用查询()方法或计数 _all_ 结果()但不能同时。而且,无论采用何种方法,您都需要利用documentation中规定的基础结果。
来源
2012-03-16 19:47:25
mjv
什么数据类型是你的'时间'列? – Matthew 2012-03-16 19:24:14
为什么你不使用“select count(*)FROM ...”?我认为服务器的负载较少。 – 2012-03-16 19:27:09