Codeigniter using foreach in view Codeigniter using foreach in view database database

Codeigniter using foreach in view


In your controller you're correctly assigning the result of the model to a variable:

$data['news'] = $this->testm->get_news();

but in your model you're ECHOING the result, not RETURNING them. SO $data['news'] is null (since the model's method doesn't return anything), and you can't iterate over null of course -> and that's the error in your view. Change your model to return an array, for example:

Public function get_news(){    $query = $this->db->query('SELECT id, date, text FROM news');    return $query->result_array();}

the text from my database does appear at the top of the page

because, indeed, you're echoing it (as pointed out above) before the views are outputted, that's why you see them before the rendered html


please try this:

in your view page:

<?php foreach($news->result() as $new) { ?>        <article class="article_text">            <p class="segment_headding"><?php echo $new->date; ?></p>                <?php echo $new->text; ?>        </article>    <?php } ?>


you just have issue in your model function foreach loop just replace that with:

$query = $this->db->query('SELECT id, date, text FROM news');$result = $query->result_array();return $result;