skarama
skarama

Reputation: 497

php sql code, foreach warning

I have the following code, not written 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?

Upvotes: 1

Views: 304

Answers (3)

Trav L
Trav L

Reputation: 15192

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';

Upvotes: 0

kylex
kylex

Reputation: 14406

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

Upvotes: 0

Pekka
Pekka

Reputation: 449475

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.

Upvotes: 4

Related Questions