首页 文章

代码点火器计数功能

提问于
浏览
1

我想要做的是我想从我的数据库中计算名为“songs_tbl”的表中的总记录数 . 所以我在控制器中写了这个函数 .

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

我收到了这个错误

致命错误:调用非对象中的成员函数count()

有什么建议吗?谢谢 .

带着敬意,

4 回答

  • 0

    您可以查询表并从表本身请求计数,如下所示:

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

    我想你正在寻找:

    $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的问题

    EDIT

    我从来没有使用过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();
    }
    

    Edit 2

    我建议的布局将是这些行(UNTESTED)使用CodeIgniter而不是聪明的:

    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();
        }
    }
    

    Controller 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));
        }
    }
    

    View songs_index.html

    <html><head></head><body>
        Total Songs: <?php echo $total_songs ?>
    </body></html>
    
  • 1

    试试这个

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

    它允许您确定特定表中的行数 .

  • 5

    你可以用它

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

相关问题