Forum Moderators: coopster

Message Too Old, No Replies

"Undefined offset:" nicer code to stop these warnings?

         

carsten888

3:27 pm on Feb 6, 2009 (gmt 0)

10+ Year Member



this code works fine, but when in php.ini error_reporting = E_ALL I get this:
Undefined offset: 0 in D:\Mijn documenten\_websites\_dev\a.....

the query returns no rows. How would be a nicer way to write this without getting those warnings.


$class_pi->db->setQuery("SELECT sectio.......LIMIT 1");
$rows = $class_pi->db->loadObjectList();
$row = $rows[0];

I could of course check for the existence of results first, which does take care of those warnings.


$class_pi->db->setQuery("SELECT sectio.......LIMIT 1");
$rows = $class_pi->db->loadObjectList();
if(count($rows)){
$row = $rows[0];
$section_id = $row->section;
}else{
$section_id = 0;
}

does anyone know nicer code to do this?

Receptional Andy

3:33 pm on Feb 6, 2009 (gmt 0)



I think the issue may be with if(count($rows)) - which will only be false if $rows is not set. Perhaps check if count returns a number >0 instead.

STeeL

3:54 pm on Feb 6, 2009 (gmt 0)

10+ Year Member



@Andy, actually if(count($rows)) will also return false if count($rows) evaluates to 0 (zero).

@carsten, you can make you code "neater" by using alternative syntax:

$section_id = (count($rows)) ? $rows[0]->section : 0;

carsten888

6:33 pm on Feb 6, 2009 (gmt 0)

10+ Year Member



Thanks for the replies.

@Steel
is that PHP5 syntax, or will that also work on php4?

Is everyone doing the getting data from the database like this? it just seems such a roundabout way.

STeeL

11:01 pm on Feb 6, 2009 (gmt 0)

10+ Year Member



Yes, it will work with PHP4, although if this is a new project, I would strongly suggest to use PHP5 as PHP4 is dead language since last summer.

Regarding database, it depends what kind of database class you are using, for example you can write your own function to return a single row:

$row = $class_pi->db->getRow('table', array('id' => 100));

carsten888

7:38 am on Feb 7, 2009 (gmt 0)

10+ Year Member



thanks