2016-03-06 20 views
0

我想使用$ query的位置。

foreach ($oppId as $o) { 

         $id = $o['opportunity_id']; 


         $query->Where("id=$id"); 


       } 

当我使用这个。显示

$query->orWhere("id=$id"); 

的所有项目,我需要这样的语句:

SELECT * FROM `opportunity` WHERE id =27 or id =28 

这是我所有的功能:

public function actionShow($type = 0, $city = 0, $client = 0) { 

    $query = (new \yii\db\Query())->select(['*'])->from('opportunity ')->innerJoin('profile_details', 'opportunity.user_id=profile_details.user_id')->orderBy('id desc'); 
    $query->Where('id !=-1'); 

    if (isset($_REQUEST['type'])) { 
     $type = $_REQUEST['type']; 



     if ($type != 0) { 
      $query->andWhere("project_type_id=$type"); 
     } 
    } 
    if (isset($_REQUEST['city'])) { 
     $city = $_REQUEST['city']; 


     if ($city != 0) { 
      $query->andWhere("state_id=$city"); 
     } 
    } 

    if (isset($_REQUEST['client'])) { 
     $client = $_REQUEST['client']; 


     if ($client != 0) { 

      $oppId = \app\models\OpportunityControl::find() 
        ->where('project_type_id = :project_type_id', [':project_type_id' => $client]) 
        ->all(); 

      foreach ($oppId as $o) { 


        $id = $o['opportunity_id']; 
        $query->orWhere("id=$id"); 
      } 
     } 
    } 

回答

1

你非常不想使用字符串在任何情况下添加到查询,因为这是成熟的SQL注入。我格式化是这样的:

... 
$params = []; 
foreach ($oppId as $o) { 
    $params[] = $o->opportunity_id; 
} 
$query->andWhere(['in', 'id', $params]); 
... 

你也应该调整你的其他查询参数,让你不通过一个字符串变量传递到SQL。

if (isset($_REQUEST['type'])) { 
    $type = $_REQUEST['type']; 

    if ($type != 0) { 
     $query->andWhere(['project_type_id' => $type]); 
    } 
} 
if (isset($_REQUEST['city'])) { 
    $city = $_REQUEST['city']; 

    if ($city != 0) { 
     $query->andWhere(['state_id' => $city]); 
    } 
} 

你正试图避免在这里什么见Yii2 guide on using variables in queries。具体做法是:

不直接像下面的情况嵌入变量,尤其是如果变量值来自最终用户的输入,因为这会让你的应用受到SQL注入攻击。

// Dangerous! Do NOT do this unless you are very certain $status must be an integer. $query->where("status=$status");

0

我使用数组做

$query->where(['or',['id'=>27],['id'=>28]]); 

但在你的情况下保存一个数组中的所有id不是poss IBLE,我用绳子做这里面的foreach

$StringWhere=''; 
    $LastElement = end($oppId); 
     foreach ($oppId as $o) 
      { 
        $id = $o['opportunity_id']; 
        $StringWhere.=' id='.$id; 
        if($o!=$LastElement) 
        { 
         $StringWhere.=' or '; 
        } 
      } 
    $query->where($StringWhere); 
0
$query->where(['or',['id'=>27],['id'=>28]]); 

我用这个和通过metola提到它完美的作品。 :)