一、控制器如下
引用use app\index\model\User;
//注意模型類名不能和控制器類名相同
public function index()
{
return $this->fetch('index');//顯示模版
}
public function add()//添加數據
{
$user=new User;
//allowField過濾無用的字符串
//validata開啟字段驗證機制
//input("post.")表示傳送過來的全部參數
if($user->allowField(true)->validate(true)->save(input("post.")))
{
return '添加成功';
}else{
return $user->getError();
}
}
二、模型內容如下
namespace app\index\model;
use think\Model;
//沒有處理任何東西,可以選加載一些要用的如自動完成
class User extends Model
{
}
三模版內容
//{:url('index/users/add')}當前控制器提交地址
//{$Request.token}隨機TOKEN需要引用REQUEST
<h2>創建用戶</h2>
<form method="post" action="{:url('index/users/add')}">
用戶:<input type="text" name="username"/><br/>
密碼:<input type="password" name="password"/><br/>
郵箱:<input type="mail" name="mail"/><br/>
<input type="hidden" name="__token__" value="{$Request.token}">
<input type="submit" value="提交"/>
</form>
四、驗證層
1、在application新建validate文件目錄
2、新建類文件user.php 注意與表名相同。與模型類名也是相同的內容如下:
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
//驗證規則變量必須是rule,更多驗證規則請參考手冊
protected $rule=[
['username','require|min:4','用戶名必須|用戶名不能少於4位'],
['mail','email','郵箱格式不正確'],
['password','require','密碼必須']
];
}