我在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)
,错误表明$query
是array
,这是不允许的。
那么,如何将这些转换为查询生成器表达式呢?
$query =Yii::app()->db->createCommand()
->select ()
->from('mosqueculturalliablee')
->where("email='" . $this->username."'")
->queryAll();
$totalRows = count($query); //get returned rows count
和循环,做:
foreach($query as $row) {
...
}
由于rep低,我无法对此发表评论,但:请不要构造这样的查询,因为它们容易受到SQL注入攻击。这是正确的方法:
$results=Yii::app()->db->createCommand('SELECT * FROM mosqueculturalliablee WHERE `email`=:email')
->queryAll(array(
':email'=>$this->username,
));