0

I have this happen all the time and I'm never quite sure why it's happening. Here is the query in my model:

$query = $this->db->query('SELECT * FROM members WHERE email = "' . $this->session->userdata('email') . '"');
        return $query;

I try to output this in my view with:

foreach($query->result() as $row) {...echo $row->name, etc.}

But I get an error:

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

I ran the profiler and my query is valid and there is data in the database to be pulled. So what am I do wrong?

3
  • 1
    honestly we need more code to adequately assist you. Commented Feb 8, 2011 at 2:09
  • exact duplicate stackoverflow.com/questions/4714802/… Commented Feb 8, 2011 at 2:37
  • No offense, jondavidjohn, but the solution was different. See the differences between the two accepted solutions. Commented Feb 8, 2011 at 15:57

2 Answers 2

3

Try this.

In your model:

function get_members()
{
    $query = $this->db->query('SELECT * FROM members WHERE email = "' . $this->session->userdata('email') . '"');
    return $query->result();
}

In your controller:

You should then be assigning the data from the database in your controller to your view like so.

$data['query'] = $this->yourmodel->get_members(); // Data['query'] will be turned into $query in your view.

$this->load->view('mytemplate', $data);

In your view:

foreach($query as $row) {...echo $row->name, etc.}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are passing the $query variable to the view, codeigniter will convert it into a keyed array if it is an object.

http://codeigniter.com/user_guide/general/views.html

Note: If you use an object, the class variables will be turned into array elements.

Edit:

In your controller:

$query = // do whatever to get the $query.
$members = array();
foreach($query->result() as $row) {
    $members[] = $row;
}
//send $members to view

In view:

foreach($members as $member) {
    echo $member['name']; // etc
}

3 Comments

So how do I not do that? I have some similar code to this and it works fine. What is the proper thing to do. Newbie here.
You should execute the query inside of the model or the controller and instead pass an array of model objects or values to the view. The view should just be a dumb data displayer.
How do I do that? Sorry for my ignorance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.