Welcome Guest, Not a member yet? Register   Sign In
Basic Syntax Question
#1

[eluser]alanphil[/eluser]
I'm starting to use Models, and have a basic syntax question. In the past I would do this in the controller:

Code:
$data['query'] = $this->db->get('contacts');
$this->load->view('welcome_message', $data);

and was able to display the data in the view with no problem. Now I'm trying to move the DB logic into a model and running into problems. In the model I have the following function:

Code:
function get_test() {
  $query = $this->db->get('contacts');
  return $query->result();
}

In the controller I have:

Code:
function index(){
    $data['query'] = $this->Mdl_contacts->get_test();
        $this->load->view('welcome_message', $data);
}

and in the view I have:

Code:
<?php foreach ($query->result() as $row): ?>
<p>&lt;?=$row->first_name?&gt; &lt;?=$row->last_name?&gt;<br />
&lt;?=$row->phone?&gt;</p>
&lt;?php endforeach; ?&gt;

My view isn't displaying the data from the DB, and I'm going around in circles looking for a good simple example like this. Thanks for any light you can shine on this simple problem. Smile

Alan
#2

[eluser]xwero[/eluser]
you already called the result method in your model so in you view the only thing you need to do is loop the $query variable like you would do with a regular array.
#3

[eluser]AgentPhoenix[/eluser]
If I'm not mistaken, I think the code you're using it trying to return the object of an object you've already returned. What I mean by that, is your code is essentially doing this:
Code:
$query->result()->result()
You've already returned the result object from the model to the controller, so it isn't valid to try and get that result object again. In my models, I generally just return the query variable and then do the various business logic in the controller.

Edit: too slow ... haha!
#4

[eluser]alanphil[/eluser]
Thank You! Thank You! :cheese:

I changed the view to:

Code:
&lt;?php foreach ($query as $row): ?&gt;
<p>&lt;?=$row->first_name?&gt; &lt;?=$row->last_name?&gt;<br />
&lt;?=$row->phone?&gt;</p>
&lt;?php endforeach; ?&gt;

and it works fine. I knew it was a simple issue, but I was chasing my tail looking in all the wrong places.

Alan




Theme © iAndrew 2016 - Forum software by © MyBB