我在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
且不允许使用。
那么,如何将这些转换为查询构建器表达式?
答案 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,
));