如何绑定params与原始查询mysql yii

时间:2014-08-22 17:23:09

标签: php mysql sql yii

我正在使用原始文本查询来生成结果。但是为了避免sql注入它想要对变量进行参数化查询,即来自& $ to,在userStat()函数中传递。

puclic function userStat($from, $to){
     $sql = "select u.user_id as ID, u.email as Email
            from User u
            where u.type = 'x'
            and u.join_date BETWEEN '$from'  AND '$to'";

    $rawData = Yii::app()->db->createCommand($sql);
    return $userData  = new CSqlDataProvider($rawData, array(
                'keyField'=>'ID',
            ));
}

现在我想将$ from和$ to绑定到文本查询($ sql)。

请帮我弄明白。

2 个答案:

答案 0 :(得分:4)

您可以使用bindParam,然后queryAll()。像下面的东西。

$sql = "select u.user_id as ID, u.email as Email
        from User u
        where u.type = 'x'
        and u.join_date BETWEEN :start  AND :end";
$rawData = Yii::app()->db->createCommand($sql);
$rawData->bindParam(":start", $from, PDO::PARAM_STR);
$rawData->bindParam(":end", $to, PDO::PARAM_STR);
$data = $rawData->queryAll();

详情bindParam。我认为它会解决你的问题。

答案 1 :(得分:1)

要绑定数据,请执行以下操作:

pubic function userStat($from, $to){
 $sql = "select u.user_id as ID, u.email as Email
        from User u
        where u.type = 'x'
        and u.join_date BETWEEN :from  AND :to";

$rawData = Yii::app()->db->createCommand($sql)->bindValues(array(':from'=>$from, ':to'=>$to));
return $userData  = new CSqlDataProvider($rawData, array(
            'keyField'=>'ID',
        )); }