在yii2

时间:2016-03-06 10:31:13

标签: yii yii2

我想在$ 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");
            }
        }
    }

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

我使用数组

mThumbnailDownloadListener

但是在你的情况下,不能保存数组中的所有ID,我使用foreach中的字符串

AThread

答案 2 :(得分:0)

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

我使用它,它完美地工作,如metola所提到的。 :)