how to solve trying to get property of non-object error

hai masters

How can I retrieving data null/empty from table ?




	public static function getNamaItemById($id)

	{

		$sql = "select itmname from item where itmid='$id'";

		$itemname = item::model()->findBySql($sql);

		return $itemname->itmname;

	}



I have the codes above and when I request from view like getNamaItemById(9) no records. so I got this error "Trying to get property of non-object". please help so I still can use that query with result empty/null not error instead.

findBySql returns NULL if nothing is found… so now you have to decide what you want to return from your method in case nothing is found… do you return false… or you return empty string… and add something like this:




...

$itemname = item::model()->findBySql($sql);

if($itemname===null)

   return '';   // <-- return empty if nothing is found

else

   return $itemname->itmname;



Thanks for reply domba,

I noticed this is happen after I change the framework to 1.1.7, in 1.1.5 there is no problem for this.

Is there any other way, or should I add checking record whether it is null or not to all function ?

Thanks

This happens when something return. and in this case I think it’s when you try to get property “itmname” so check it.

thanks boy, you are rite, it is about return, if null it show error.

Domba solution is correct already, just curious why this promblem came out when I switch to use Yii 1.1.7.

the return type or logic changed between 1.1.7 and your old version?? maybe…

But from code, I think all the thing you do is using AR… seem like fine.