Home  >  Article  >  Backend Development  >  ThinkPHP code sharing for adding data

ThinkPHP code sharing for adding data

小云云
小云云Original
2018-03-09 13:04:151184browse

This article mainly shares with you the code for adding data in ThinkPHP, hoping to help everyone.

<?php
//后台商品控制器
namespace Admin\Controller;
use Think\Controller;
//Controller父类:ThinkPHP/Library/Think/Controller.class.php
class GoodsController extends Controller{
    //添加商品。"add"是一个关键字,所以方法名不能是"add"。
    function tianjia(){
        $goods = D(&#39;Goods&#39;);
        //一、 关联数组方式添加数据
        $arr = array(
            &#39;goods_name&#39; => &#39;黑莓手机&#39;,   //关联数组下标goods_name必须与数据表中的字段对应,否则该字段会被过滤。
            &#39;goods_price&#39; => 3400,
            &#39;goods_number&#39; => 14,
            &#39;goods_weight&#39; => 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 product controller):

<?php
//后台商品控制器
namespace Admin\Controller;
use Think\Controller;
//Controller父类:ThinkPHP/Library/Think/Controller.class.php
class GoodsController extends Controller{
    //添加商品
    function tianjia(){
        $goods = D(&#39;Goods&#39;);
        //两个逻辑:展示表单、收集表单信息
        if(!empty($_POST)){  //如果是点击了添加(提交)按钮(提交给自己本身的页面)。
            //收集表单信息
			//$z = $goods -> add($_POST);
            $data = $goods -> create(); //收集表单信息、非法字段过滤、表单自动验证、信息过滤处理(跨站脚本攻击)等等。
            $z = $goods -> add($data);
            if($z){
                //$this ->redirect (地址分组/控制器/操作方法, 参数数组, 间隔时间, 提示信息)
                $this ->redirect(&#39;showlist&#39;, array(), 2, &#39;添加商品成功!&#39;);   //地址showlist表示当前控制器下的showlist。
            }else{
                $this ->redirect(&#39;tianjia&#39;, array(), 2, &#39;添加商品失败!&#39;);
            }
        }else{
            $this -> display();//展示添加商品表单
        }
    }
}

Related recommendations:

jquery Ajax implements Select dynamically adding data instance analysis

Ajax dynamically adds data to the drop-down list

jQuery EasyUI adds data Detailed explanation of examples

The above is the detailed content of ThinkPHP code sharing for adding data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is a PHP handleNext article:What is a PHP handle