我正在尝试获取用户在过去24小时内发送的邮件数量。我的代码只返回整数1,但这不是真的。我究竟做错了什么? 我的日期格式为:2012-03-01 10:57:32
谢谢!
function get_quota($data)
{
$sql = "select * FROM messages WHERE user_id = {$data['id']}
AND time > DATE_SUB(now(), INTERVAL 1 DAY)";
$this->db->query($sql);
$count=$this->db->count_all_results();
return $count;
}
答案 0 :(得分:4)
在我看来,你正在返回大量数据(使用select *)来计算消息!这是带宽和处理能力的可怕浪费。做
function get_quota($data)
{
$sql = "select count(*) as howmany FROM messages WHERE user_id = {".$data['id']."} AND time > DATE_SUB(now(), INTERVAL 1 DAY)";
$myResults = $this->db->query($sql);
retrn $myResults->row()->howmany;
}
并返回结果
编辑 - 您的错误是$data['id']
未在双引号内进行评估。
答案 1 :(得分: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();
对于第二种方法,我不是100%如何/如果文字'DATE_SUB()...'有效地被SQL传递和执行(它必须因为它是一个SQL函数),但这是另一个问题;为了安全起见,请使用注释掉的语法,该语法使用单个 where 表达式作为单个字符串传递。
这个答案的要点是你需要使用 query() 方法或 count _all_ 结果() 但不是两者兼而有之。而且,无论采用何种方法,您都需要利用documentation中规定的基础结果。