Welcome Guest, Not a member yet? Register   Sign In
passing data from a controller to my view
#1

[eluser]Unknown[/eluser]
Hi,

I am new to CI and am currently trying to pass my query from my model to my controller and then into my view but I think I am getting confused as to what is an object etc.

My Model:

function get_band($id)
{
$this->db->where('id', $id);
$query = $this->db->get('bands');
if ($query->num_rows() > 0)
{
return $query;
}
}

My Controller:

function admin_edit_form($id)
{
$this->load->model('form_model');
$data['query'] = $this->form_model->get_band($id);

$data['base'] = $this->base;
$data['css'] = $this->css;
$data['title'] = "Results";
$this->load->view('admin_edit_view' , $data);
}

My View:

foreach ($query->result_array() as $row):
echo $row['myfieldname'];
endforeach;

Now how would I do this so that the foreach was done in the controller. Would it be a foreach loop as above and if so how would I assign each fieldname to the $data object. Then how would I reference it in the view, $this->query->myfieldname or $this->data->myfieldname.

I tried to dump_var(data) but got nothing.

I think the main problem is that I haven't really got my head round models and obects so I need to do some more reading.

Thanks
#2

[eluser]TheFuzzy0ne[/eluser]
Welcome to the CodeIgniter community!

$this should be avoided within views if you can. Rather than doing the foreach in the controller, why not do it in the model and have the model format the data exactly how you need it?

Code:
function get_band($id)
{
    $this->db->where('id', $id);
    $result = $this->db->get('bands');
    return $result->result_array();
}

Or you could do something like this in your controller:
Code:
$data['query'] = $this->form_model->get_band($id);
$data['query'] = $data['query']->result_array(); # PHP 4

#OR

$data['query'] = $this->form_model->get_band($id)->result_array(); # PHP 5
#3

[eluser]Unknown[/eluser]
Thank you for the response. I am using PHP 5

So after I have loaded the model ($this->load->model(‘form_model’)Wink, do I call the model with:

$data[‘query’] = $this->form_model->get_band($id);

or

$data = $this->form_model->get_band($id);

and if so what foreach loop would I use to assign the data to variables to use in my view?

foreach ($query->result_array() as $row):
$data['myfieldname'] = $this->row->myfieldname;
endforeach;

Do you know of any good books that deal with objects. Someone on this forum mentioned:

Object-Oriented PHP: Concepts, Techniques and Code by Peter Lavin.

Thank you




Theme © iAndrew 2016 - Forum software by © MyBB