ThinkPHP简单增删改查

来源:互联网 发布:入职程序员感觉干不了 编辑:程序博客网 时间:2024/04/27 17:06

框架里面最简单的必须要知道的莫过于增删改查(CURD),我们写面向过程写php的时候,每次都要重复写sql语句。面向对象可以大大提高效率,ThinkPHP中的model类已经写好了增删改查的类,我们只需要直接调用即可。

打开你项目内的lib文件夹,新建一个NewAction.class.php类,我们开始书写我的类了。

<?php
    //定义一个新闻信息的类
   class NewAction extends CommonAction{
        //从数据库获取信息,在模板显示
        public function index{
            $New = D('new');//快速实例化model类
            //查询数据
            $list = $New ->limit(5)->select();
            $this->assign('list', $list); //给模板赋值
            $this->display(); //加载模板
        }
        //添加数据
        public function insert(){
            $New = D('new');
            //判断是否添加成功
            if($New->create()){
                $New->time=time();//添加时间赋值
                $New->ip = $_SERVER['REMOTE_ADDR'];//ip地址
                if($New->add()){
                    $this->success("添加数据成功!");
                }else{
                    $this->error("添加数据失败!");
                }
            }else{
                $this->error($Form->getError());
            }
            $this->display();//加载添加模板
        }
    }
    //修改信息
   public function edit(){
       $New = D("new");
       $info=$New->where('id='.$_GET['id'])->find();
        if($info){
            $this->assign("info",$info);
            $this->display();
        }else{
            $this->error("编辑的不存在");
        }
    }
    //修改信息内容
    public function update(){
            $New = D("new");
            if($New->create()){
                $this->uptime = time();//修改时间
                if($New->save()!==false){//判断是否修改成功
                    $this->success("修改成功!");
                }else{
                    $this->error("修改失败!");
                }
            
      }
       //删除信息
    public function del(){
        if(!empty($_REQUEST['id'])){
            $New = D("new");
            $vo=$New->where('id='.$_REQUEST['id'])->delete();
            if($vo!==false){
                $this->success("删除成功!");
            }else{
                $this->error("删除失败!");
            }
        }
        $this->display();
    }
}
?>
 

很简单的增删改查,我们只需要在模板中写入ThinkPHP模板标签,或直接加载值就可以了。

0 0
原创粉丝点击