Yii:findAllByAttributes()使用$个属性与$个条件+ $个参数:

cnjp1d6j  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(172)

我想知道的是findAllByAttributes()的第一个参数可以避免SQL注入,还是只有使用$condition + $params才能防止SQL注入?
当您选择使用其中一个时,还有其他考虑因素吗?

使用$attributes

$result = Setting::model()->findByAttributes(
   array(
       'name'=>$name,
       'lang_id'=>$lang_id
   )
);

使用$condition + $parms

$result = Setting::model()->findByAttributes(
   '',
   'name =:name AND lang_id = :lang_id',
   array(
       ':name' => $name,
       ':lang_id' => lang_id
   )
);
ru9i0ody

ru9i0ody1#

findByAttributes()中使用$attributes可以防止SQL注入,因此这是非常安全的:

$result = Setting::model()->findByAttributes([
    'name' => $name,
    'lang_id' => $lang_id,
]);

这通常是首选的语法,因为它比预准备语句更简单、更短,但它并没有涵盖所有可能的情况--它适用于简单匹配,但对于任何不同于=的运算符,你需要使用$condition

$result = Setting::model()->findByAttributes(
    [
        'name' => $name,
        'lang_id' => $lang_id,
    ],
    'priority >= :priority',
    [':priority' => $priority]
);

相关问题