phpcodeignitermodel-view-controllerforeachresultset

Invalid argument supplied for foreach() CodeIgniter view file


I am getting an error in the CodeIgniter view:

Invalid argument supplied for foreach()

My view code:


<html>
<head>
    <title><?=$page_title?></title>
</head>
<body>
    <?php foreach($result as $row):?>
    <h3><?=$row->title?></h3>
    <p><?=$row->text?></p>
    <br />
    <?php endforeach;?>
</body>

</html>

Solution

  • Test the $result if it is an array, before using foreach on it. Your result may be false since your database query failed, or returned no result.

    if (is_array($result))
    {
        foreach($result as $row)
        {
            /* ... */
        }
    }