在一个场景中,我需要知道查询将返回的记录集的计数,这在编码器中可以由$query->num_rows()
或$this->db->count_all_results()
完成。哪一个更好,两者之间的区别是什么?
对于num_rows()
,您首先执行查询,然后可以检查您获得了多少行。另一方面,count_all_results()
只给您查询将产生的行数,但不给您实际的结果集。
// num rows example
$this->db->select('*');
$this->db->where('whatever');
$query = $this->db->get('table');
$num = $query->num_rows();
// here you can do something with $query
// count all example
$this->db->where('whatever');
$num = $this->db->count_all_results('table');
// here you only have $num, no $query
$this->db->count_all_results
是活动记录查询的一部分(准备查询,只返回数字,而不是实际结果)。
$query->num_rows()
在结果集对象上执行(在从DB返回结果之后)。
我们也可以使用
return $this->db->count_all('table_name');
或
$this->db->from('table_name');
return $this->db->count_all_result();
或
return $this->db->count_all_result('table_name');
或
$query = $this->db->query('select * from tab');
return $query->num_rows();
Which one is better and what is the difference between these two
这对我来说几乎是不可能的,有人只是想获得记录的数量,而不需要重新触摸或执行涉及相同资源的另一个查询。此外,这两个函数使用的内存毕竟是相同的,因为对于count_all_result
,您仍然执行get
(在CI AR术语中),所以我建议您使用另一个(或使用count()代替),这给您带来了可重用性的好处。
有两种方法来计算查询将返回的记录总数。首先这个
$query = $this->db->query('select blah blah');
return $query->num_rows();
这将返回查询带来的行数。
第二
return $this->db->count_all_results('select blah blah');
count_all_results将要求再次运行查询。
结果总数
$this->db->count_all_results('table name');
简写为;
$this->db->get('table_name')->num_rows();
这将获得行/记录的数量。但是,您也可以使用搜索参数;
$this->db->select('col1','col2')->where('col'=>'crieterion')->get('table_name')->num_rows();
但是,应该注意的是,如果应用下面的命令,您将看到非常糟糕的错误;
$this->db->get('table_name')->result()->num_rows();
$sql = "select count(*) as row from login WHERE firstname = '" . $username . "' AND password = '" . $password . "'";
$query = $this->db->query($sql);
print_r($query);exit;
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}