我想你正在寻找:
$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
我建议的布局将是使用 CodeIgniter 没有 smarty 的这些行(未测试):
Model 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));
}
}
查看 song_index.html
<html><head></head><body>
Total Songs: <?php echo $total_songs ?>
</body></html>