1

Having a bit of trouble getting my For Each function to display all the values from a DB into a view. Where am I going wrong? Not a back-end pro, nor did I write it. Database table is extremely simple, one column named id. I want to display each of the rows in my for each.

I have a custom MY_Controller.php file and in the _construct I have this, which fills in variables globally across the site.

$this->country_zones = $this->Studios_model->get_studios();

Model:

function get_studios()
{
    //this will alphabetize them
    $this->db->order_by('id', 'ASC');

    $query  = $this->db->get('gc_studio_zones');

    foreach ($query->result() as $row)
    {
        $countries = $row->id;
    }
    return $countries;
}

In my view:

<?php foreach($this->$country_zones as $country):?>
    <li><?php echo $country['countries']->id;?></li>
<?php endforeach;?> 

Error:

Cannot access empty property...etc

1 Answer 1

1

I think you have a typo in your view regarding your loop variable, it should be this->country_zones:

<?php foreach($this->country_zones as $country):?>
    <li><?php echo $country->id;?></a></li>
<?php endforeach;?>

Besides, your Model isn't returning an array, but only the last id. You need to push the values to your result array:

function get_studios()
{
    //this will alphabetize them
    $this->db->order_by('id', 'ASC');

    $query  = $this->db->get('gc_studio_zones');

    $countries = array();
    foreach ($query->result() as $row) {
        $countries[] = $row;
    }
    return $countries;
}
Sign up to request clarification or add additional context in comments.

7 Comments

Good eye...now I have another error: Severity: Warning Message: Invalid argument supplied for foreach()
This worked when I removed ->id from the echo in the <li>. However, only the first character is being displayed for each value...?
@MikeBarwick Well, because you only store the id in the results array of your model function. I updated the answer, now every returned row is saved. This means that the view has to be modified as well with the values you want to show there (currently it'll output only id again).
Confused. So everything in your answer should work? It doesn't...gives this error: Cannot use object of type stdClass as array in...etc
And what I meant by only shows the first character. For example, in Column "id" I have one row with the value, "Canada". When this value was pulled into the view, only the character "C" was shown.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.