How To Use Findbyattributes Function

Hello buddies;

Could you please compile my code in your mind and detect my mistake and inform me?

Mu code is something like below:




$user = User::model()->findByAttributes(array(

            'username' => ':username',

        ), array(

            ':username' => 'mail@mail.mail',

        ));



And the error is:

Thanks in advance

Check: http://www.yiiframework.com/doc/api/1.1/CActiveRecord/#findByAttributes-detail and you will see what you are missing.

When I change the code to below:




$user = User::model()->findByAttributes(array(

            'username' => ':username',

        ), '', array(

            ':username' => 'mail@mail.mail',

        ));



I get this error


CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: SELECT * FROM `tbl_user` `t` WHERE `t`.`username`=:yp0 LIMIT 1

Thanks Bjorn, but I read that topic before but no change to my knowledge




$user = User::model()->findByAttributes(array(

            'username' => 'mail@mail.mail',

        ));



It’s not documented clearly but CActiveRecord::findByAttributes() takes care of parameter binding (in fact, it delegates the job to CDbCommandBuilder::createColumnCriteria()). You need to use third parameter only when second parameter (the additional condition) is not empty.

Oh I didn’t know that! thanks Phtamas

You may also try this,


$user = User::model()->findByAttributes(array(),

    			'username=:username',

    			array(':username'=>'test@mail.in''));