• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cannot access query results in view: Message: Undefined variable

Hey all,

when home/index page is loaded, this method is called:

public function index(){
            $home = new Home();
            $query_results = $home->find('all'); //I would rather use static method, like Home::find but if I define a static method in model, then I can't access $this property in it, therefore forgoing the built in active record pattern.
               $defaults = array('head' => 'Welcome to HM Law Group', 'subhead' => 'The attorney who meets your expectations');
            $result = array_merge($defaults,$query_results);
            $this->template->render_content('template', '/homes/index', $result);

This method is called in model:

public function find($param){
            if(is_null($param) || $param === 'all'){
                $resources = $this->db->get('homes');  
                 return $resources->result();  
            return null;

So result() returns an array of objects translated from field names. So I presume I can now access the property like $row->title.

I also have this autoloaded template class:

public function __get($name){
        return isset($this->_data[$name]) ? $this->_data[$name] : NULL;

    public function __set($name, $value){
        $this->_data[$name] = $value;

    function set($name, $value){
        $this->template_data[$name] = $value;

    function render_content($template = '', $view = '' , $data = array(), $return = FALSE){              
        $this->CI = get_instance();  

        $this->title = "Default Title";  
        $this->subtitle = "Default Subtitle";
        $this->_data = array_merge($this->_data, $data);
        $this->set('yield', $this->CI->load->view($view, $this->_data, TRUE));    
        $this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));

        return $this->CI->load->view($template, $this->template_data, $return);

But when I try to access the objects in view, I get undefined variable:

<h1>&lt;?php echo $head; ?&gt;</h1>
<h2>&lt;?php echo $subhead; ?&gt;</h2>

    foreach($_data as $row){
        echo $row->title;
           echo $row->description;
           echo $row->link;

alhough I am able to access $head and $subhead, which contained hard coded values declared in controller.

I am not sure how I can access my database results in view.

Thanks for response.

This fix for this was assigning the object that resulted from result() in an associative array of an array object:

$data = $home->find('all');
$options['records'] = $data;

At that point, the associatve array become available as a variable in view and that variable held an object of key/value pairs from the query, so foreach can be used to iterate through the objects indexed in the array (e.g. $row->title).

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.