开发者

php sql code, foreach warning

I have the following code, not 开发者_如何学Cwritten bymyself, but I am wondering if you could spot anything wrong with it?

$query =    "SELECT * from #__properties_type where published = 1 AND parent =        ".$Category_id." OR parent = 0";

$db->setQuery( $query );                

$types = $db->loadObjectList();

$nP = count($types);

$mitems[0]->id=0;

$mitems[0]->name='Type';

    foreach ( $types as $item ) {

        $mitems[] = $item;

    }

It seems to work fine but sometimes I will see a random Warning: Invalid argument supplied for foreach() in etc/etc/etc/

Any ideas?


Your loadObjectList function seems to return a non-array sometimes, maybe when the SQL query fails.

Quick fix:

if (is_array($types))
foreach ( $types as $item ) {

        $mitems[] = $item;

    }

but you should look for the deeper cause why the function fails, and handle the error accordingly if there is one.


It probably means your $types variable isn't being set. This will set a PHP warning off.


Unless $mitems[0] is predefined before your code snippet, there's no way PHP can know about $mitems[0] contains an object, hence $mitems[0]->id will throw an warning.

To solve this:

$mitems[0] = new YourObject();
$mitems[0]->id=0;
$mitems[0]->name='Type';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜