实现思路:
1、POST提交数据(用户名称和密码)
2、获取POST请求获取到的数据,并验证(用户名验证,判断是否重名)、密码加密(一般使用MD5加密)。
3、将验证完成的数据存入数据库,并返回用户的ID(用于判断存储是否成功)。
实现代码:
1、表单代码:
// method="post" : 发送POST请求 action="{:url('admin/add')}: 提交的地址 <form class="form form-horizontal" id="form-admin-add" method="post" action="{:url('admin/add')}"> <div class="row cl"> <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>管理员名:</label> <div class="formControls col-xs-8 col-sm-9"> <input type="text" class="input-text" value="" placeholder="" id="username" name="username"> </div> </div> <div class="row cl"> <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>密码:</label> <div class="formControls col-xs-8 col-sm-9"> <input type="password" class="input-text" autocomplete="off" value="" placeholder="密码" id="password" name="password"> </div> </div> <div class="row cl"> <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3"> <input class="btn btn-primary radius" type="submit" value=" 提交 "> </div> </div> </form>
2、获取提交参数
<?php namespace app\admin\controller; use think\Controller; class Admin extends Base{ //增加用户的方法 public function add(){ //1、判断是否是post的提交 if($this->request->isPost()){ //2、获取POST提交的数据 $data = \input('post.'); //3、获取验证对象 $validate = \validate('AdminUser'); //调用check()方法开启验证 if(!$validate->check($data)){ $this->error($validate->getError()); } //4、查询数据,判断是否重名,get(获取数据库数据,参数是数组(查询的条件)) $user = \model('AdminUser')->get(['username'=>$data['username']]); if($user != null){ $this->error('用户名已存在'); } //5、密码加密 $data['password']= \md5($data['password'].'_#sing_ty'); $data['status'] = 1; try{ //5、调用模型类的add()保存数据 $id = \model('AdminUser')->add($data); }catch(Exception $e){ $this->error($e->getMessage()); } // 根据返回的id值进行判断,插入数据是否成功。 if($id){ $this->success('id='.$id.'的用户新增成功'); }else{ $this->error('添加失败!'); } }else{ // 跳转到注册页面 return $this->fetch(); } } } ?>
3、验证类的主要代码
<?php namespace app\common\validate; use think\Validate; // 继承 Validate 类 class AdminUser extends Validate{ // 指定验证规则: require:必填 max:20 最大长度为20 protected $rule = [ 'username' => 'require|max:20', 'password' => 'require|max:20', ]; } ?>
4、model类的主要代码
<?php namespace app\common\model; use think\Model; class AdminUser extends Model{ public function add($data){ // 判断数据格式是否是数组 if(!is_array($data)){ \exception('传递数据不合法'); } // allowField: 过滤post数组中的非数据表字段数据。 save:保存数据。 $this->allowField(true)->save($data); return $this->id; } } ?>
以上代码就完成了一个简单的添加用户账号的功能,主要就是插入数据库数据、获取数据库数据、密码加密、字段验证等功能。