用户注册时加密密码后,无法成功插入数据 [ 2.0 版本 ]
AR类
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class RegistForm extends ActiveRecord
{
public $password_repeat;
public static function tableName()
{
return 'user';
}
public function rules()
{
return [
[['username','password','password_repeat'], 'required', 'message' => '填写内容不能为空'],
['password','compare']
];
}
public function attributeLabels()
{
return [
'username' => '用户名',
'password' => '重复密码',
'password_repeat' => '密码'
];
}
}
控制器中的方法
public function actionRegist()
{
$model = new RegistForm();
if ($model->load(Yii::$app->request->post())) {
$model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
if ($model->save()) {
$this->redirect(['login', 'msg' => '注册成功!']);
}
} else {
return $this->render('regist', ['model' => $model]);
}
}
好吧,问题已解决,是因为save的过程中还要经过一次validate,然而我的密码已经哈希了,跟再次输入的密码配对不上,所以无法插入,顺道给大家说下,$model->getErrors()才是查出错误的办法。感谢大家的回答,本帖终结
共 5 个回答
-
print_r($model->errors);
共 8 条回复@474352380 model->load()没有错,就是我load之后就save的话,数据是能正常插入数据库。但是假如我对任何的字段进行修改的话,就save失败
* @see generatePasswordHash() */ public function validatePassword($password, $hash) { if (!is_string($password) || $password === '') { throw new InvalidParamException('Password must be a string and cannot be empty.'); } if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches) || $matches[1] < 4 || $matches[1] > 30 ) { throw new InvalidParamException('Hash is invalid.'); }
你查下这下方法。。
@474352380 纳闷是没有报错,就是save 返回了 false,字段应该是没错,都是password
@474352380
object(app\models\RegistForm)[60]
public 'password_repeat' => string '123' (length=3)
private '_attributes' (yii\db\BaseActiveRecord) =>array (size=2) 'username' => string 'uer' (length=3) 'password' => string '$2y$13$94VOHsmS3IXYFaV2qFoelubuIti9Ifzj2SfRBkUp7bW7gteCH6.Rq' (length=60)
private '_oldAttributes' (yii\db\BaseActiveRecord) => null
private '_related' (yii\db\BaseActiveRecord) =>array (size=0) empty
private '_errors' (yii\base\Model) => null
private '_validators' (yii\base\Model) =>object(ArrayObject)[61] private 'storage' => array (size=2) 0 => object(yii\validators\RequiredValidator)[64] ... 1 => object(yii\validators\CompareValidator)[66] ...
private '_scenario' (yii\base\Model) => string 'default' (length=7)
private '_events' (yii\base\Component) =>array (size=0) empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
-
dingjj2010 回答于 2016-08-19 14:51 举报
一般情况下,load后的数据不符合。建议开启调试,看一下log具体是什么。
vVvlife 东莞
最后登录:2016-10-07
在线时长:8小时38分
- 粉丝1
- 金钱700
- 威望0
- 积分780