【问题标题】:Yii2 : Can I bind an array to an IN() condition in join?Yii2:我可以将数组绑定到连接中的 IN() 条件吗?
【发布时间】:2016-06-23 11:19:59
【问题描述】:

我会尝试下面的查询,但不确定是否防止 sql 注入?

        $status = [1, 2, 3];
        $param = implode(', ', $status);

        $rows = (new \yii\db\Query())
            ->select('*')
            ->from('user')
            ->leftJoin('post', "post.user_id = user.id AND post.some_column = $value AND post.status IN ($param)");
            ->all();

返回预期结果但可能发生sql注入。我的 IN 条件是 IN (1, 2, 3)

        $rows = (new \yii\db\Query())
            ->select('*')
            ->from('user')
            ->leftJoin('post', "post.user_id = user.id AND post.some_column = :sid AND post.status IN (:param)", [':param' => $param, ':sid' => $value]);
            ->all();

只比较数组中的第一个元素,因为看起来像这样IN ('1, 2, 3') 它由单个字符串组成,不检查数组中的第二个元素,只对第一个元素起作用。

我参考了下面的链接,但不知道如何实现这个条件。

Can I bind an array to an IN() condition?

请给出如何在On部分join(PDO/Yii2/mysql)中使用IN() Condition的解决方案。

【问题讨论】:

  • 好的,我删除了我的答案,因为where 条件与on 条件不同,您需要on 条件。对了,我开这个issue,有兴趣的可以:github.com/yiisoft/yii2/issues/11827

标签: php mysql yii2 sql-injection


【解决方案1】:

基于this issue:

        $rows = (new \yii\db\Query())
        ->select('*')
        ->from('user')
        ->leftJoin('post', ['post.user_id' => new \yii\db\Expression('user.id'), 'post.some_column' => $sid, 'post.status' => $statuesArray]);
        ->all();

【讨论】:

    【解决方案2】:

    Yii2 可以通过将条件作为数组传递来创建参数化的 IN 条件,即:

    ['post.status' => $status]
    

    但是,如Yii guide 中所述,将您的连接条件转换为数组格式将不起作用:

    请注意,where() 的数组格式旨在将列与值进行匹配,而不是将列与列匹配,因此以下内容无法按预期工作:['post.author_id' => 'user.id'],它将匹配 post.author_id 列值与字符串'user.id'。这里推荐使用更适合join的字符串语法:

    'post.author_id = user.id'

    由于您使用的是INNER JOIN,因此将连接条件放入WHERE 而不是ON 的结果将在语法上相等,如INNER JOIN condition in WHERE clause or ON clause? 中所述。对于readability and ease of maintenance,您可以将表列的比较留在连接条件中:

    $rows = (new \yii\db\Query())
            ->select('*')
            ->from('user')
            ->innerJoin('post', 'post.user_id = user.id')
            ->where(['post.some_column' => $value, 'post.status' => $status])
            ->all();
    

    【讨论】:

    • 对不起,我在我的项目中使用了leftJoin。我在我的问题中写了查询只是演示。我在我的项目中使用了同样的情况。如何在OnCondition上使用IN()
    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    相关资源
    最近更新 更多