由於要與資料庫的user表進行關聯才能新增,TP5內部已經做好了處理只需要新建application/index/model/User.php檔案
寫入程式碼如下:
<?php namespace app\index\model; use think\Model; class User extends Model { protected $pk = 'user_id'; }
由上一節可知註冊提交的路徑和方式為:
<form action ="/public/index.php/index/regist/regist" method="post">
#繼續編輯application/index/controller/Regist.php
寫一個regist方法:
<?php //用户注册 public function regist(){ //实例化User $user = new User; //接收前端表单提交的数据 $user->user_name = input('post.UserName'); $user->user_sex = input('post.UserSex'); $user->user_tel = input('post.UserTel'); $user->user_email = input('post.UserEmail'); $user->user_address = input('post.UserAddress'); $user->user_birth = input('post.UserBirth'); $user->user_passwd = input('post.UserPasswd'); $user->user_signature = input('post.UserSignature'); $user->user_hobby = input('post.UserHobby'); //进行规则验证 $result = $this->validate( [ 'name' => $user->user_name, 'email' => $user->user_email, 'sex' => $user->user_sex, 'tel' => $user->user_tel, 'address' => $user->user_address, 'birth' => $user->user_birth, 'password' => $user->user_passwd, ], [ 'name' => 'require|max:10', 'email' => 'email', 'sex' => 'number|between:0,1', 'tel' => 'require', 'address' => 'require', 'birth' => 'require', 'password' => 'require', ]); if (true !== $result) { $this->error($result); } //写入数据库 if ($user->save()) { return $this->success('注册成功'); } else { return $this->success('注册失败'); } }
#全部驗證通過$result才會等於true,有一個錯誤就回傳對應的string類型的錯誤訊息
input('post.UserName')取得的數值根據(提交的方式).(表單的nama值的屬性)
這樣註冊功能就完成了
效果展示如下:
資料庫展示如下:
下一節