ThinkPHP 的CURD 基本操作

木子小僧發表於2015-05-29

  說起CURD,懂點SQL的人都知道,就是增刪改查,做業務系統的時候,往往離不開這CURD,最近也是剛剛接觸ThinkPHP,ThinkPHP的靈活性是比原生PHP好用的多,下面我就簡單的介紹一下我的學習心得。

      學習ThinkPHP對MySQL的操作,首先你要有MySQL,然後又PHP的執行環境。

      wamp可以幫你解決配置的麻煩,關於wamp資料很多,百度就可以了。

      下面就簡單介紹一下ThinkPHP的增刪改查的過程。

      一、建立資料庫,命名為t_user。

           程式碼為:

     

 DROP TABLE IF EXISTS `t_user`;
      CREATE TABLE `t_user` (
      `userid` int(11) NOT NULL,
      `username` varchar(25) DEFAULT NULL,
      `usersex` varchar(6) DEFAULT NULL,
      `userage` int(6) DEFAULT NULL,
      PRIMARY KEY (`userid`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  建立一個專案,命名為thinkPHP_Text,匯入thinkphp核心包。

  配置index.php檔案。

     啟動專案,自動生成目錄。如下圖:

     

  二、關於thinkphp的add()操作。

           建立index的action檔案,命名為IndexController.class.php,寫一個函式insertUser(),在控制層中,你要得到前臺的傳值。

/**
* 新增使用者資訊
* 編碼時間:2015-05-28
*/
public function insertUser($id,$name,$sex,$age){
$this->db(1,"DB_CONFIG1")->db(1);
$condition = array(//定義要新增的資料,放在一個陣列裡,命名為$condition
'userid' => $id,
'username' => $name,
'usersex' => $sex,
'userage' => $age,
);
$addInfo = $this->db(1,"DB_CONFIG1")->add($condition);//執行sql語句,insert
if($addInfo){
header("Location: http://localhost/thinkPHP_Text/index.php"); 
}
echo $this->getLastSql();//除錯用,輸出sql語句
return $addInfo; 
}
/**

         在model層中,記住命名方式,在本次配置中,命名為UserModel.class.php,對應的:

 1  /**
 2    * 新增使用者資訊
 3    * 編碼時間:2015-05-28
 4  */
 5     public function insertUser($id,$name,$sex,$age){
 6             $this->db(1,"DB_CONFIG1")->db(1);
 7             $condition = array(//定義要新增的資料,放在一個陣列裡,命名為$condition
 8                 'userid' => $id,
 9                 'username' => $name,
10                 'usersex' => $sex,
11                 'userage' => $age,
12             );
13             $addInfo = $this->db(1,"DB_CONFIG1")->add($condition);//執行sql語句,insert
14             if($addInfo){
15                     header("Location: http://localhost/thinkPHP_Text/index.php"); 
16                 }
17             echo $this->getLastSql();//除錯用,輸出sql語句
18             return $addInfo;                
19         }

 這就是新增操作的核心程式碼。

具體的程式碼請到下面的連結下載,詳細見註釋:

http://pan.baidu.com/s/1hq7wfnm

相關文章