yii中查询构建器中的mysql_fetch_assoc和mysql_num_rows

时间:2013-11-22 09:06:33

标签: php mysql yii

我在yii框架中有一个查询,我想将其转换为查询构建器

部分代码:

        $sql ="SELECT * FROM `mosqueculturalliablee` WHERE `email` ='$this->username'";
        $query = mysql_query($sql,$connect);
        if ($query === FALSE) {
            trigger_error(mysql_error());
        }
        $numrows = mysql_num_rows($query);
        if ($numrows!=0)
        {
            //while loop
            while ($row = mysql_fetch_assoc($query)){
                $email = $row["email"];
                $password = $row["password"];
            }

我以这种方式转换前两行:

          $query =Yii::app()->db->createCommand()
        ->select ()
        ->from('mosqueculturalliablee')
        ->where("email='" . $this->username."'")
                ->queryAll();

我的问题出在mysql_num_rows($query)mysql_fetch_assoc($query),错误表示$queryarray且不允许使用。

那么,如何将这些转换为查询构建器表达式?

2 个答案:

答案 0 :(得分:2)

queryAll()返回查询结果的所有行。所以你可以这样做:

$query =Yii::app()->db->createCommand()
        ->select ()
        ->from('mosqueculturalliablee')
        ->where("email='" . $this->username."'")
                ->queryAll();
$totalRows = count($query); //get returned rows count

并循环,执行:

foreach($query as $row) {
   ...
}

答案 1 :(得分:0)

由于低代表,我无法对此发表评论,但是:请不要构造类似的查询,因为它们容易发生SQL注入攻击。这是正确的方式:

$results=Yii::app()->db->createCommand('SELECT * FROM mosqueculturalliablee WHERE `email`=:email')
->queryAll(array(
    ':email'=>$this->username,
));