Sonu S
Sonu S

Reputation: 23

yii database query inside loop

I didn't get the correct filter out for the following action. Here $val is an array of checked values. But the query executes only for the last element of the array even though I used the foreach loop. Please, can anyone help me?

 if( isset($_POST['state']) && count($_POST['state']) > 0  ){
    foreach($_POST['state'] as $row => $val ){
       $criteria = new CDbCriteria; 
       $criteria->select='*'; 
       $criteria->condition='pjt_user_id=:pjt_user_id && pjt_pdt_status=:pjt_pdt_status';
       $criteria->params=array(':pjt_user_id'=> $user_id, ':pjt_pdt_status'=> $val);    
       $criteria -> order = 'pjt_id';           
       $projects= ProjectModel::model() -> findAll($criteria);



     }
$this->render('index', array('projects'=>$projects));

Upvotes: 1

Views: 416

Answers (2)

Martin Komara
Martin Komara

Reputation: 767

This would be better - much more readable:

if (isset($_POST['state']) && count($_POST['state']) > 0 ) {  
    $criteria = new CDbCriteria;
    $criteria->addInCondition('pjt_pdt_status', $_POST['state']);
    $criteria->addColumnCondition(array('pjt_user_id' => $user_id));
    $criteria->order = 'pjt_id';
    $projects = ProjectModel::model()->findAll($criteria);     
}

Upvotes: 0

Sonu S
Sonu S

Reputation: 23

Thanks Martin Komara.... I got the solution ... I just use OR condition in SQL.

if(isset($_POST['state']) && count($_POST['state']) > 0 ){  


        $i = 0;
        foreach($_POST['state'] as $data){  
           $condit[":$data"] = $data; 
           if($i!=0){
              $var   .= ' || ';
           }
           $var   .= " pjt_pdt_status=:$data";
           $i++;                
        }
        $var = ' AND (' .$var.' )';     
    }   
    $criteria = new CDbCriteria;    
    $criteria->select='*'; 
    $criteria->condition='pjt_user_id=:pjt_user_id' .$var ;
    $criteria->params=$condit;
    $criteria -> order = 'pjt_id';          
    $projects= ProjectModel::model() -> findAll($criteria);     

Upvotes: 1

Related Questions