ThinkPHP 自動建立資料、自動驗證、自動完成詳細例證介紹(十九)

來源:互聯網
上載者:User
ThinkPHP 自動建立資料、自動驗證、自動完成詳細例子介紹(十九)


1:自動建立資料

//$name=$_POST['name'];
//$password=$_POST['password']; ---這個註冊頁面傳過來的POST值
下面用了自動穿件create方法就可以不用這個,會行動綁定
$user =M('User');
$User->create(); //會將傳過來的$_POST資料對應到資料庫的欄位
$user->add(); //就可以直接寫入


2:自動驗證(只需要在Model類裡面定義$_validate屬性)

使用步驟(註冊驗證User表)


一:建立User表自訂的Mode --->Home\Lib\Model\UserModel.class.php

//注意:code username password....都是你表單裡面的name值,要對應
//表單裡面欄位名字定義的
class UserModel extends Model{
protected $_validate=array(
array('code','require','驗證碼必須填寫!'),
array('code','checkCode','驗證碼錯誤!',0,'callback',1), //使用回呼函數checkCode
array('username','require','使用者必須填寫!'),
array('username','','使用者已經存在',0,'unique',1),
array('username','/^\w{6,}$/','使用者名稱必須6個字母以上',0,'regex',1),
array('repassword','password','確認密碼不正確',0,'confirm'),
);


protected functioncheckCode($code){
if(md5($code)!=$_SESSION['code']){
return false;
}else{
return true;
}
}
}
?>


//控制請值對應的註冊方法

class RegisterAction extends Action{
public function doReg(){

$user=D('User'); //大D方法是會先去找你自訂的Mode,(使用上面建立的UserModel.class.php類)
//如果有有自訂的用自訂的,否則用原始的 D等同M M!=D

if(!$user->create()){//會自動去驗證 返回一個布爾類型,成功則自動建立資料
$this->error($user->getError());//擷取具體錯誤資訊
}
$lastId=$user->add();
if($lastId){
$this->redirect('Index/index');
}else{
$this->error('使用者註冊失敗');
}


}
}
?>

3:自動完成(做留言的例子)
步驟:
一:建立Message表自訂的Mode --->Home\Lib\Model\MessageModel.class.php

class MessageModel extends RelationModel{
protected $_auto=array(
array('time','time',1,'function'),
array('uid','getId',1,'callback')

);
protected functiongetId(){
return $_SESSION['id'];
}
}
?>
二:控制器中

class MessageAction extends Action{
public function doLiuyan(){
$message=D('Message');
//$message->time=time();
//$message->uid=$_SESSION['id']; 這2個值將在自訂MessageModel中自動填滿完成

$message->add(); //返回值是新增的id號
}
}
?>







  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.