views:

136

answers:

5

I try to write a site with CodeIgniter but I've a problem with PHP. I'm sure that it's so simple and can't be wrong. But I don't know bugs from , just a newbie of CodeIgniter :)

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

I've a bug from this file :

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/helloworld_view.php

Line Number: 6

thanks in advance for reading this :)

+1  A: 

$result is not array.

Try to check it with is_array before foreach.

And debug why $result is not array :P

confiq
+2  A: 

The variable you supply to the foreach loop has to be an array. You can skip the foreach if the value of the variable supplied is not an array with the solution below.

<?php if(is_array($result)): ?>
<?php foreach($result as $row):?>  
<h3><? echo $row->title; ?></h3>  
<p><? echo $row->text; ?></p>  
<?php endforeach;?>  
<?php endif; ?>
Robert Hurst
This will stop the error but it will not help him work out what is going on. Alex Lawford has made the best guess here, either he is trying to use the database object or he has FALSE from his model somewhere.
Phil Sturgeon
+2  A: 

Try foreach($result->result() as $row) - it could be you're trying to iterate through the object returned by Codeigniter's active record.

Alex Lawford
A: 

If you are wondering what could be in the variable, output it!

var_dump($result);

That will instantly tell you what is going on. My guess, you have returned FALSE somewhere from your model, or you are using the DB object and not result() or result_array() (as suggested by Alex).

Phil Sturgeon
A: 

If you are using the tutorial at : http://net.tutsplus.com/tutorials/php/codeigniter-basics/

Then it is line 5 of the helloworld_model.php, it should be:

if ($query->num_rows() == 0)

not

if ($query->num_rows() > 0)
Dave Albert