Sepideh
Sepideh

Reputation: 133

yii Trying to get property of non-object

I have a table in my mysql db

What I am trying to this. See here below the result I excpect:

average=100.1

I am trying with

$res = Users::model()->findAllBySql("SELECT avg(number) AS total FROM tbl_users",array());
echo $res->total;

but give me error Trying to get property of non-object when run this query in sql on php my admin its work!!

Upvotes: 0

Views: 165

Answers (2)

jdkraftz
jdkraftz

Reputation: 71

In your Users model, define total. If you use alias in query, you need to define it in the model else it will give you this error. That is the reason it works in phpmyadmin but not here.

class Users  extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public $total; // define total here 
    public function tableName()
    {

Upvotes: 0

Goodnickoff
Goodnickoff

Reputation: 2267

findAllBySql() method returns an array. http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAllBySql-detail

If you want to get only one record then you shoud use findBySql() method.

I guess here better use DAO:

$res = Yii::app()->db->createCommand("SELECT avg(number) AS total FROM tbl_users")->queryRow();

if(!empty($res)){
    echo $res['total']
}

Upvotes: 1

Related Questions