简体   繁体   中英

How to Yii SQL Like

I wish to do a search function for my yii project. I found out in yii that is a function called addSearchCondition() , then I tried to do the search function.

public function actionSearchApp(){

    $searchapp = $_POST['searchapp'];


    $id = Yii::app()->user->getState('id');
    $models = GamesDevelopersApp::model()->findAll('developer_id='.$id);
    array('models'=>$models);
    foreach($models as $model){ 
        $gametitle = CHtml::encode($model->gametitle);

    }

    $search = new CDbCriteria();
    $search->addSearchCondition($gametitle.'LIKE:'.$searchapp);
    $result = GamesDevelopersApp::model()->findAll($search);
    print_r($result);
}

Error Message: Missing argument 2 for CDbCriteria::addSearchCondition()

Any Suggestion for doing SQL Like in Yii ? or any good example for doing search function in yii

UPDATED

public function actionSearchApp(){
        $searchapp = $_POST['searchapp'];

        $id = Yii::app()->user->getState('id');
        $models = GamesDevelopersApp::model()->findAll('developer_id='.$id);

        $search = new CDbCriteria();
        $search->addSearchCondition('gametitle', $searchapp); 
        $result = GamesDevelopersApp::model()->findAll($search); 

        print_r($result);

}

Yes it searched, but now it search all data from gametitle, how to make it "where developer_id='id' "?

you almost did that. Here is the correct code:

 $search = new CDbCriteria();
    $search->addSearchCondition($gametitle, $searchapp); //this add the condition and escapes it properly
    $result = GamesDevelopersApp::model()->findAll($search); //here you pass the criteria
    print_r($result)

;

The answer of Samuel Liew is totally wrong and SQL injectable.

I successful tried the code and output I need :

Still have to thanks Nikola suggestion

public function actionSearchApp(){

        $searchapp = $_POST['searchapp'];

        $id = Yii::app()->user->getState('id');
        $models = GamesDevelopersApp::model()->findAll('developer_id='.$id);

        $search = new CDbCriteria();
        $search->addSearchCondition('gametitle', $searchapp); 
        $search->addCondition('developer_id='.$id);
        $result = GamesDevelopersApp::model()->findAll($search,array('developer_id'=>$id)); 

        print_r($result);

}

use addCondition() for the where developer_id='id' Thanks =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM