Welcome Guest, Not a member yet? Register   Sign In
Invalid argument foreach()
#1

[eluser]Medikal[/eluser]
Hey guys, first time poster here. Extremely new to codeigniter, decided to take a chance with it as it seemed alot more intuitive than zend/cakephp. I have to say the support on the forums and the extremely vast user guide is absolutely amazing, and has already helped me through alot as I'm teaching myself.

I ran into a minor error, not sure exactly why I get the error:
Message: Invalid argument supplied for foreach()

My model:
Code:
function listposts()
            {
                
                $query = $this->db->get('posts');
                
                if ($query->num_rows() > 0)
                    {
                        return $query->result();
                    }
                
            }
My controller:
Code:
function index()
    {
        
        $data['rows'] = $this->posts_model->listposts();
        $this->load->view("index_view", $data);
        
    }

and the view, erroring at line 10: (the foreach line)
Code:
<?php
foreach ($rows as $row) {
   echo '<h1>' . $row['title'] . '</h1><br>
   ' . $row['text'] . '';
}  
?&gt;
#2

[eluser]kaejiavo[/eluser]
Hi Medikal,

you are trying to access an object as an array.
Have another look at the user guide here.
#3

[eluser]Medikal[/eluser]
Well, after sorting it out and mashing my head against the keyboard, turns out it was because there were no entries in the database. /cry

Thanks for the link mawi.
#4

[eluser]tonanbarbarian[/eluser]
your problem is that your model listposts method is only returning a value if your database returns a value.
So in the case where a result is found listposts returns an array of rows
but if nothing is found in the query then it is returning nothing
in which case $data['rows'] would probably be null

try this
Code:
function listposts() {
    $query = $this->db->get('posts');
    if ($query->num_rows() > 0) {
        return $query->result();
    }
    return array();
}
#5

[eluser]kaejiavo[/eluser]
Code:
function listposts()
            {
                
                $query = $this->db->get('posts');
                
                if ($query->num_rows() > 0)
                    {
                        //This line returns an array of objects(!)
                        return $query->result();
                    }
                
            }
// view:
&lt;?php
foreach ($rows as $row) {
   //echo '<h1>' . $row['title'] . '</h1><br>
   //   ' . $row['text'] . '';

   // as $rows contains an array of _objects_, you have to use:
   echo '<h1>' . $row->title . '</h1><br>
   ' . $row->text . '';

}  
?&gt;

Alternatively you can use in your model:
Code:
return $query->result_array();
and leave your view as it is.




Theme © iAndrew 2016 - Forum software by © MyBB