【小(xiǎo)編推薦】ThinkPHP3.2——表單合₩‍法性檢測

2014-06-26   | &→☆™nbsp; 發布者:梁國(guó)芳 &n ‌•Ωbsp; |   查看✔∞¥β(kàn):3320次

Thinkphp

在處理(lǐ)表單提交的(de)數(shù)據的(de)時(shí)↓¶<β候,建議(yì)盡量采用(yòng)Think\Model類提供的(de≤≤)create方法首先進行(xíng)數(shù)據創建,然後再寫₹‍₽ 入數(shù)據庫。

create方法在創建數(shù)據的(de)同時(shí),可(kπ♦ě)以進行(xíng)更為(wèi)安全的(de)ε™'☆處理(lǐ)操作(zuò),而且這(zhè)一(y•πα£ī)切讓你(nǐ)的(de)表單處理(lǐ)變得(de<¶×)更簡單。

使用(yòng)create方法創建數(shù)‌±據對(duì)象的(de)時(shí)候,可(kě)以使用(yòng₽≠‌)數(shù)據的(de)合法性檢測,支持兩種方式:

一(yī)、可(kě)以配置insertFields 和(hé) ←×φ<updateFields屬性

可(kě)以分(fēn)别為(wèi)新增和(hé)>♣λ∞編輯表單設置insertFields和(hé) updateFields屬性,使用(yòng)create方法創建數(shù)據β₩對(duì)象的(de)時(shí)候,¶>不(bù)在定義範圍內(nèi)的(de)屬性将直接丢棄,避Ω♥§α免表單提交非法數(shù)據。

insertFields 和(hé) updateFields屬 ‍  性的(de)設置采用(yòng)字符串(逗号分(fēn)割多™α‍(duō)個(gè)字段)或者數(shù)組的(de)方±δ★式。

設置的(de)字段應該是(shì)實際的(de)數(shù)據表字段,而不(b&≠∑ù)受字段映射的(de)影(yǐng)響。例如↕±₽(rú):

  1. namespace Home\Model;
  2. class UserModel extends \Think\Model{
  3. protected $insertFields = array('account','password','nickname','email');
  4. protected $updateFields = array('nickname','email');
  5. }

定義後,調用(yòng)add方法寫入用(yòng)戶數(shù)據的(&≥de)時(shí)候,隻能(néng)寫入'account','password','nickname​‍','email'這(zhè)幾個(gè)字段,編輯的(de)時(shí)候隻能(né≠✘ng)更新'nickname','email'兩個(gè)字段。

在使用(yòng)的(de)時(shí)候,我們調用(yò✘✘λ←ng)create方法的(de)時(shí)候,會(huì)根£ ↑​據提交類型自(zì)動識别insertFi↓÷elds和(hé)updateFields屬性:

  1. D('User')->create();

二、直接調用(yòng)field方法

如(rú)果不(bù)想定義insertFieldσ's和(hé)updateFields屬性,可(kě)以在調用(yòn→∑‍g)create方法之前直接調用(yòng↓α)field方法,例如(rú),實現(xiàn)和(hé)上(shàng)∏×面的(de)例子(zǐ)同樣的(de)作(zuò)用(yòng): ‌±& 在新增用(yòng)戶數(shù)據的(de)時(shí)候,使∑δ用(yòng):

  1. M('User')->field('account,password,nickname,emailλ≠©')->create();

而在更新用(yòng)戶數(shù)據的&δ(de)時(shí)候,使用(yòng):

  1. M('User')->field('nickname,email')->create();

這(zhè)裡(lǐ)的(de)字段也(yě)是(shì)實際的(de)數(sδ↑hù)據表字段。

field方法也(yě)可(kě)以使用(y♦♣òng)數(shù)組方式。

使用(yòng)字段合法性檢測後,你(nǐ)不(bπ♥←ù)再需要(yào)擔心用(yòng)戶在提£> ×交表單的(de)時(shí)候注入非法字段☆®‍♥數(shù)據了(le)。