yii queryScalar()与mysql查询?

时间:2016-01-02 07:16:09

标签: php yii

我想找到已登录用户的匹配ID和电子邮件的用户角色。下面是我的wbuser类

我收到了以下错误

Error 500
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

这是我的代码

<?php

class WebUser extends CWebUser {
    public $role;
    public $role2;

    public function getRole2() {
        if ($this->role2 === null) {
            // Here you need to get User role
            $this->role2 = Yii::app()->db->createCommand("SELECT email FROM {{students}} WHERE id=:id AND role=1")->queryScalar(array(':id' => Yii::app()->user->id));
        }

        return $this->role2;
    }
    public function getRole(){
        if ($this->role === null) {
            // Here you need to get User role
            $this->role = Yii::app()->db->createCommand("SELECT role FROM {{students}} WHERE id=:id AND email=':email'")->queryScalar(array(':id' => Yii::app()->user->id,':email' => $this->role2,));
       } 
        return $this->role;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这种方式

$this->role2 = Yii::app()->db->createCommand()
->select('email')
->from( '{{students}}' )
->where('id=:id AND role=1', array(':id'=>$id));
->queryScalar();

并且对于第二个查询,请尝试

$this->role2 = Yii::app()->db->createCommand()
->select('role')
->from( '{{students}}')
->where('id=:id AND email=:email', array(':id'=>$id, ':email'=> $this->role2));
->queryScalar();