在yii中如何编写插入查询

时间:2012-11-20 10:39:21

标签: php yii insert

在yii中,我正在创建登录模块。成功登录后,我必须检索当前登录用户userid,并希望将该用户标识插入到另一个'logintransLog'表中,该表具有userid作为具有外键关系的属性。那么在yii中,如何检索当前的用户ID并将其插入另一个表?请帮帮我......


如果只有userid正确且密码错误,我想将userid插入表'loginAttempt',以便记录用户尝试登录的时间。那么我该如何实现呢?我有actionlogin方法:

public function actionLogin()
{
    $model=new LoginForm;
    $command = Yii::app()->db->createCommand();

    // if it is ajax validation request
    if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }

    // collect user input data
    if(isset($_POST['LoginForm']))
    {
        $model->attributes=$_POST['LoginForm'];
        // validate user input and redirect to the previous page if valid
        if($model->validate() && $model->login())
        {
                $command->insert('trans', array(
                    'id'=>Yii::app()->user->getId(),
                //'Ipaddress'=>Yii::app()->user->getIpaddress(),
                ));
            $this->redirect(Yii::app()->user->returnUrl);
        }

    }
    // display the login form
    $this->render('login',array('model'=>$model));
}      

请帮帮我

2 个答案:

答案 0 :(得分:11)

1st,Easy and right:制作模型logintransLog表并使用:

$log = new logintransLog();
$log->user_id = $user->id;
$log->created = date('Y-m-d H:i:s');
$log->save();

第二,快点 - 使用createCommand:

$sql = "insert into logintransLog (user_id, created) values (:user_id, :created)";
$parameters = array(":user_id"=>$user->id, ':created' => date('Y-m-d H:i:s'));
Yii::app()->db->createCommand($sql)->execute($parameters);

// try this, if any validation failed it was count as login attempt
if ($model->validate() && $model->login()) {
        $command->insert('trans', array(
           'id'=>Yii::app()->user->getId(),
         //'Ipaddress'=>Yii::app()->user->getIpaddress(),
        ));
        $this->redirect(Yii::app()->user->returnUrl);
} else {
        $command->insert('loginAttempt', array(
           'username'=>$model->username,
           'Ipaddress'=>$_SERVER['REMOTE_ADDR'],
        ));
}

答案 1 :(得分:0)

还有另一种方式 使用 $log->insert(); 代替 $log->save();