2011-11-16 99 views
1

我想要做的是我想從我的數據庫中名爲「songs_tbl」的表中計算總記錄數。所以我在控制器中寫了這個函數。代碼點火器計數功能

private function getHeaderInfo() 
{ 
     $total_songs = $songs->count('distinct songs_tbl.song_id'); 
     $this->mysmarty->assign('total_songs',$total_songs); 
} 

我得到這個錯誤

Fatal error: Call to a member function count() on a non-object in

什麼建議嗎?謝謝。

與問候,

+1

哪裏$歌曲從何而來? – karlipoppins

+0

'$ songs'爲空。 – xdazz

+0

是因爲$歌曲嗎?是的,我忘了delcare $歌曲,我應該申報什麼? – spotlightsnap

回答

5

我認爲你正在尋找:

$this->db->count_all('songs_tbl'); 

,或者如果你想要的不同之處在那裏,你需要做這樣的事情:

$this->db->select('song_id'); 
$this->db->distinct(); 
$this->db->from('songs_tbl'); 
$query = $this->db->get(); 
return $query->num_rows(); 

由於有/是?使用count_all_results()功能和DISTINCT

編輯

我從來沒有使用Smarty的,但基於問題的代碼問題我想這樣的事情可能會奏效,請糾正我,如果我錯了:

private function getHeaderInfo() 
{ 
    $total_songs = get_all_songs();// This function should be called through a model 
    $this->mysmarty->assign('total_songs',$total_songs); 
} 

function get_all_songs(){ //THIS SHOULD BE IN A MODEL 
    $this->db->select('song_id'); 
    $this->db->distinct(); 
    $this->db->from('songs_tbl'); 
    $query = $this->db->get(); 
    return $query->num_rows(); 
} 

編輯2

我建議的佈局將採用無笨Smarty的東西沿着這些路線(未經測試):

型號Song.php

class Song extends CI_Model { 
    //Constructor and other functions 

    function count_all_songs(){ 
     $this->db->select('song_id'); 
     $this->db->distinct(); 
     $this->db->from('songs_tbl'); 
     $query = $this->db->get(); 
     return $query->num_rows(); 
    } 
} 

控制器Songs.php

class Song extends CI_Controller { 
    //Constructor and other functions 

    function index(){ //This could be any page 
     $this->load->model('Song'); //Could be in constructor 
     $total_songs = $this->Song->count_all_songs(); 
     $this->load->view('songs_index.html', array('total_songs' => $total_songs)); 
    } 
} 

查看songs_index.html

<html><head></head><body> 
    Total Songs: <?php echo $total_songs ?> 
</body></html> 
+0

謝謝。但我用smarty,我怎麼能在模板方面執行該功能? – spotlightsnap

+0

$ total_songs = get_all_songs(); //此函數應該通過模型調用 $ this-> mysmarty-> assign('total_songs',$ total_songs); 這兩行應該與函數get_all_songs在同一個模型文件中?如果我放入相同的模型文件,當我執行時,我得到了空白頁。 – spotlightsnap

+0

我應該把什麼東西放進控制器?我把上面的代碼放在我的模型文件中,並在模板端執行這個函數<{$ total_songs}>,沒有任何反應。我沒有看到任何數量和錯誤。 – spotlightsnap

1

你可以查詢表,從表本身請求數,像這樣:

$result = mysql_query(SELECT count(*) FROM songs_tbl); 
1

試試這個

echo $this->db->count_all('songs_tbl'); 

它允許你確定一個特定的行數表。

0

您可以使用此

$query = $this->db->get('distinct'); 
     if($query->num_rows()) 
     { 
      return $query->num_rows(); 
     }else{ 
      return 0; 
     }