Welcome Guest, Not a member yet? Register   Sign In
Problem passing variables to view
#1

[eluser]Unknown[/eluser]
Hi. I am trying to do a simple exercise where I get information out of a database and print it in my view. The following code works without a problem:

Code:
<?php

class Testmodel_controller extends Controller {

    function Index()
    {
        $this->load->model('Testmodel', '', TRUE);
        $data=$this->Testmodel->get_all();
        foreach($data->result() as $item):
        echo $item->name;
        echo " ";
        endforeach;
    }
}
?>

However, when I try the following:

Code:
<?php

class Testmodel_controller extends Controller {

    function Index()
    {
        $this->load->model('Testmodel', '', TRUE);
        $data=$this->Testmodel->get_all();
        $data=$data->result();
        $this->load->view('testview', $data);
    }
}
?>

along with:

Code:
<html>
<head>
<title>This is a test</title>
</head>
<body>
<ul>
&lt;?php foreach($data as $item):?&gt;

<li>&lt;?php echo $item->name;?&gt;</li>

&lt;?php endforeach;?&gt;
</ul>
&lt;/body&gt;
&lt;/html&gt;

I think I am doing the right thing; the documentation says to send an array of objects to the view, so I am turning $data into an array of objects before I send it. However, I get the following errors:

Quote:A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/testview.php

Line Number: 7

and,

Quote:A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/testview.php

Line Number: 7

Do you guys know what I'm doing wrong?

Thanks!!
#2

[eluser]Marcelo Lipienski[/eluser]
Try this Smile

Your controller

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

Your view
Code:
if ($query->num_rows() > 0) {
  foreach($query->result() as $row) {
    echo $row->your_field;
  }
}




Theme © iAndrew 2016 - Forum software by © MyBB