Greg McNulty
Greg McNulty

Reputation: 1466

Why does this model return "non-object error", when it worked in the controller?

In my controller I went from getting the data right there (which worked fine):

$data['query'] = $this->db->query("MY DB QUERY");  
$this->load->view('shopci_view', $data);

to grabbing the data from a class model function:

    class Shopci_model extends CI_Controller {

      function __construct()
      {
        parent::__construct(); //model constructor
      }

      //display sale itmes on shopci_view.php
      function sale_items()
      {    

        $query = $this->db->query('MY DB QUERY - SAME AS ABOVE');

        return $query->result();
      }

  }

new controller function:

//load model, auto connect to db
$this->load->model('Shopci_model', '', TRUE);    
//Display items for sale
$data['query'] = $this->Shopci_model->sale_items();  
$this->load->view('shopci_view', $data);  

ERROR:

Fatal error: Call to a member function result() on a non-object in shopci_view

This is the line in the view that worked before I switched to the model (didn't change view):

<?php foreach($query->result() as $row): ?>

Any help is appreciated.

Thank You.

Upvotes: 0

Views: 54

Answers (2)

Cody Covey
Cody Covey

Reputation: 1060

In your model you want to return the data to pass to the controller. So in your model you would have

function sale_items()
{
    $query = $this->db->query(SAME AS OLD);
    return $query;
}

and then your controller will be the same and your foreach in your view should be the following

<?php foreach ($query as $row): ?>

Upvotes: 1

Laurence
Laurence

Reputation: 60068

In your model you return the $query as a result() array to the controller.

So you cannot then use 'foreach $query->result()' again - because you have already done that;

This should work

  <?php foreach($query as $row): ?> 

OR if you want - just change the model from

 return $query->result(); 

to

 return $query;

Upvotes: 1

Related Questions