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

时间:2015-01-02 11:29:54

标签: php mysql codeigniter

当我在浏览器上运行时遇到这个致命的错误请解决我的问题...我不知道这个代码有什么问题.........致命错误:调用成员函数where()在非对象上

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

模型

<?php

        class News extends CI_Model
        {
        function Users(){
        //call model constructor

        parent::Model();
        //load database
        $this->load->database();
        }

        public function get_all_news(){

        $this->db->get('news');
        if($query->num_rows()>0){
        //return result set as associate array

        return $query->result_array();


        }

        }
        public function getnews($field,$param){

        $this->db->where($field,$param);

        $query=$this->db->get('news');
        // return result set as accosiate array

        return $query->result_array();
        }

        public function getnumnews(){
        return $this->db->count_all('news');
        }

        }

        ?>

控制器

<?php
    class News_data extends CI_Controller{

    public function Users(){

    // load controller parent

    parent::Controller();

    // load ‘Users’ model



    }

    public function index(){
    $this->load->model('News');
    $data['users']=$this->News->getnews('id <',5);

    $data['numusers']=$this->News->getnumnews();

    $data['title']='Displaying user data';
    $data['header']='User List';

    // load ‘Show_data’ view
    $data['title']='Display data';
    $this->load->view('Show_data',$data);

    }

    }
    ?>

视图

</head>

<body>

<h1><?php echo $header;?></h1>

<ul>

<?php foreach($users as $user):?>

<li>

<p><?php echo $user['id'].' '.$user['title'].' '.$user['tetxt'];?></p>

</li>

<?php endforeach;?>

</ul>

<p><?php echo 'Total number of users :'.$numusers;?></p>

</body>

</html>

?>

2 个答案:

答案 0 :(得分:2)

您可能无法在此处初始化数据库对象$this->db $this->db->where($field,$param);或您的$this->db为空。

答案 1 :(得分:0)

请在模型构造函数中加载数据库或通过autoload.php加载

请修改您的型号,如下所示

class News extends CI_Model
        {

        function __construct(){
          $this->load->database();
        }

        function Users(){
        //call model constructor

        parent::Model();
        //load database
        $this->load->database();
        }

        public function get_all_news(){

        $this->db->get('news');
        if($query->num_rows()>0){
        //return result set as associate array

        return $query->result_array();


        }
}