2009-08-03 42 views
56

我對CodeIgniter和Active Record非常陌生,特別是我知道如何在普通SQL中很好地完成這項工作,但我正在努力學習。CodeIgniter Active Record - 獲取返回的行數

如何從我的表中選擇一些數據,然後計算使用CodeIgniters Active Record類返回的行數?

謝謝, 湯姆。

回答

107

看一看結果功能here

$this->db->from('yourtable'); 
[... more active record code ...] 
$query = $this->db->get(); 
$rowcount = $query->num_rows(); 
+0

我幾個小時都在b my我的腦袋,我不記得這個函數的名字......而且在官方文檔中也不容易找到。我在`get_where`方法產生的對象上使用`print_r`來猜測函數的名字! =) – aL3xa 2011-08-04 18:53:52

+0

@Residuum你能幫我解決這個問題[查詢數量行不返回正確的行數時,結果是不是空](https://stackoverflow.com/ question/45397106/query-num-rows-not-returning-correct-number-of-row-when-result-is-empty) – 2017-07-30 07:32:12

35

,如果你只是想獲得的所有行的計數表中的

$table_row_count = $this->db->count_all('table_name'); 
+0

非常感謝。 – 2013-09-09 09:06:33

8

只是愛閱讀文檔兒子!

$query->num_rows(); 
15

如果您只需要行數的查詢,不需要實際行數據,使用count_all_results

echo $this->db 
     ->where('active',1) 
     ->count_all_results('table_name'); 
29

這正好給你的模型:

public function count_news_by_category($cat) 
{ 
    return $this->db 
     ->where('category', $cat) 
     ->where('is_enabled', 1) 
     ->count_all_results('news'); 
} 

這是我目前項目的一個例子。

根據benchmarking這個查詢的工作比,如果你做以下更快:

$this->db->select('*')->from('news')->where(...); 
$q = $this->db->get(); 
return $q->num_rows(); 
2

這也是一個非常有用的功能,如果你正在尋找一個行或數據與在條件的影響

function num_rows($table) 
    { 
     return $this->db->affected_rows($table); 
    } 
3

您可以通過兩種不同的方式做到這一點:

1. $this->db->query(); //execute the query 
    $query = $this->db->get() // get query result 
    $count = $query->num_rows() //get current query record. 

    2. $this->db->query(); //execute the query 
     $query = $this->db->get() // get query result 
     $count = count($query->results()) 
      or count($query->row_array()) //get current query record. 
2
$this->db->select('count(id) as rows'); 
$this->db->from('table_name'); 
$this->db->where('active',1); 
$query = $this->db->get(); 
foreach($query->result() as $r) 
{ 
    return $r->rows; 
} 
0
function getCount(){ 
    return $this->db->get('table_name')->num_rows(); 
} 
相關問題