ThinkPHP 添加資料的代碼分享

來源:互聯網
上載者:User
本文主要和大家分享ThinkPHP 添加資料的代碼,希望能協助到大家

<?php//後台商品控制器namespace Admin\Controller;use Think\Controller;//Controller父類:ThinkPHP/Library/Think/Controller.class.phpclass GoodsController extends Controller{    //添加商品。"add"是一個關鍵字,所以方法名不能是"add"。    function tianjia(){        $goods = D('Goods');        //一、 關聯陣列方式添加資料        $arr = array(            'goods_name' => '黑莓手機',   //關聯陣列下標goods_name必須與資料表中的欄位對應,否則該欄位會被過濾。            'goods_price' => 3400,            'goods_number' => 14,            'goods_weight' => 104,        );        $z = $goods -> add($arr);   //傳回值$z是添加成功記錄的主鍵id值。        dump($z);                //二、 AR方式添加資料,通過Model屬性值添加(其實屬性並未定義)        //以下是 “對象給本身不存在的成員屬性賦值”與給私人屬性賦值一致,其會調用魔術方法__set();,在__set()方法裡邊會把成員屬性的值賦予給data成員,進而在add()方法裡邊實現資料的添加        $goods -> goods_name = "小米手機";  //屬性值goods_name必須與資料表中的欄位對應,否則該欄位會被過濾。        $goods -> goods_price = "2900";        $goods -> goods_weight = "109";        $z = $goods -> add();        echo $z;        $this -> display();    }   }

GoodsController.class.php(Goods商品控制器):

<?php//後台商品控制器namespace Admin\Controller;use Think\Controller;//Controller父類:ThinkPHP/Library/Think/Controller.class.phpclass GoodsController extends Controller{    //添加商品    function tianjia(){        $goods = D('Goods');        //兩個邏輯:展示表單、收集表單資訊        if(!empty($_POST)){  //如果是點擊了添加(提交)按鈕(提交給自己本身的頁面)。            //收集表單資訊//$z = $goods -> add($_POST);            $data = $goods -> create(); //收集表單資訊、非法欄位過濾、表單自動驗證、資訊過濾處理(跨站指令碼攻擊)等等。            $z = $goods -> add($data);            if($z){                //$this ->redirect (地址分組/控制器/操作方法, 參數數組, 間隔時間, 提示資訊)                $this ->redirect('showlist', array(), 2, '添加商品成功!');   //地址showlist表示當前控制器下的showlist。            }else{                $this ->redirect('tianjia', array(), 2, '添加商品失敗!');            }        }else{            $this -> display();//展示添加商品表單        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.