Yii cactiverecord 如何检查数据库中是否存在记录
在yii中,我使用安全问题创建密码重置功能。首先,用户需要输入他的电子邮件id。我在Yii cactiverecord 如何检查数据库中是否存在记录,yii-cactiverecord,Yii Cactiverecord,在yii中,我使用安全问题创建密码重置功能。首先,用户需要输入他的电子邮件id。我在views->User1as中创建了emailform.php <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'email-form', 'enableClientValidation'=>true, )); echo CHtml::textField('email'); echo CHtml:
views->User1
as中创建了emailform.php
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'email-form',
'enableClientValidation'=>true,
));
echo CHtml::textField('email');
echo CHtml::submitButton('Send');
$this->endWidget();
现在我想检查用户表中是否存在此电子邮件id。如果有,那么我想向他展示一个安全问题。如何实现这一点?这将帮助您开始,您可以在控制器中放置类似的方法,并创建一个带有密码字段的视图
public function actionPassword() {
if(isset($_POST['email'])) {
$record=User::model()->find(array(
'select'=>'email',
'condition'=>'email=:email',
'params'=>array(':email'=>$_POST['email']))
);
if($record===null) {
$error = 'Email invalid';
} else {
$newpassword = 'newrandomgeneratedpassword';
$record->password = $this->hash_password_secure($newpassword);
$record->save(); //you might have some issues with the user model when the password is protected for security
//Email new password to user
}
} else {
$this->render('forgetPassword'); //show the view with the password field
}
}
这与PDO类似:
$query = 'SELECT * etc.. WHERE email = :email';
$stmt = DB::prepare($query);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->execute();
etc...
这不安全
然后
if( empty($model) )
{
// exit code
}
else
{
// success block
}
如果您使用的是CActiveRecords,检查记录是否存在的正确方法是使用函数,而不是find()函数
$condition = 'email_d=:emailId';
$params = array(':emailId' => $emailId);
$emailExists = User::model()->exists($condition,$params);
if( $emailExists) )
{
//email exists
}
else
{
// email doesn't exist
}
要检查数据库中的记录,可以使用两个选项
$exists = ModelName::find()->where([ 'column_name' => $value])->andWhere(['column_name' => $value])->exists();
//returns true or false
及
检查
但是请,请,请不要使用md5来保护密码!同意,首选Bcrypt。这只是一个例子。
$condition = 'email_d=:emailId';
$params = array(':emailId' => $emailId);
$emailExists = User::model()->exists($condition,$params);
if( $emailExists) )
{
//email exists
}
else
{
// email doesn't exist
}
$exists = ModelName::find()->where([ 'column_name' => $value])->andWhere(['column_name' => $value])->exists();
//returns true or false
$exists = ModelName::findOne(["column_name" => $value,"column_name"=>$value]);
if ($exists)
{
// exit
}
else
{
// not exist
}