2011-11-16 98 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; 
     }