1

im trying get results through a for loop.but i am getting above error.what can be the reason?.I have db named news. it contains columns as id,title,description.

My controller

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

}

Model

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

View

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

 <?php }} ?>
colombo
  • 520
  • 2
  • 9
  • 24
  • The error message is very specific about the reason. You tried to call the method result() on null instead of an object. In other words: $NewsData is null. Find out why. – Gordon Dec 06 '17 at 07:52
  • Always check if you have results or not. If not don't loop through the results or display an error message. – Alex Dec 06 '17 at 18:38

1 Answers1

2

Please correct your code using from below line.

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

       <?php }
} ?>
Ayyappa amara
  • 437
  • 3
  • 16