Codeigneitor错误:在null上调用成员函数result()

时间:2017-12-06 07:49:41

标签: php codeigniter

我试图通过for循环获得结果。但我得到了错误。可能是什么原因?。我有db命名新闻。它包含作为id,title,description的列。

我的控制器

class news extends CI_Controller
{
    function  __construct() {

        parent::__construct();

        $this->load->helper('url');
        $this->load->database();
        $this->load->helper('form');
        $this->load->library('upload');
        $this->load->model('news_model');
    }

    function index(){

        $this->load->model('news_model');
        $this->data['NewsData'] = $this->news_model->get_news();
        $this->load->view('site/cms/news',$this->data);
    }

}

模型

class news_model extends CI_Model
{
    public function __construct() 
    {
        parent::__construct(); // Construct CI's core so that you can use it
        $this->load->database();

    }

     function get_news(){


        $this->db->select('*');
        $this->db->from('news');
        $news_details = $this->db->get();
        return $news_details;
    }
}

查看

<?php if($NewsData->result() > 0){
                    foreach($NewsData->result() as $add){?>
<p><?php echo $add->title; ?></p>

 <?php }} ?>

1 个答案:

答案 0 :(得分:2)

请使用以下行修改您的代码。

<?php if($NewsData->num_rows() > 0){
       foreach($NewsData->result() as $add){?>
           <p><?php echo $add->title; ?></p>

       <?php }
} ?>