TP中的增删改查操作

<?php

namespace app\index\controller;

 

use think\Db;

/**

 * 框架核心

 * 查询构造器

 * 系统学习数据库的增删改查:curd

 */

class Demo5{

    /**

     * 单条查询

     */

    public function find(){

        $res= Db::table('cash_channel')

        ->field('id,title')

        //->field(['id'=>'编号','title'=>'标题'])

        ->where('id',1)

        ->find();

 

        dump(is_null($res)?'没有数据':$res);

    }

 

    /**

     * 多条查询

     */

    public function select(){

        $res=Db::table('cash_channel')

        ->field('id,title')

        ->where([['id','>=',2]])

        ->select();

 

        if(empty($res)){

            return '没有数据';

        }else{

            foreach ($res as $row){

                dump($row);

            }

        }

    }

 

    /**

     * 单条插入

    */

    public function insert(){

        $data=[

            'title'=>'新数据',

            'code'=>'xsj',

            'account_fields'=>'代付需要的数据'

        ];

 

        return Db::table('cash_channel')

        //->insert($data,true);//mysql数据库时后面加true sql语句为REPLACE INTO

        //->data($data)->insert();//data方法包装增强安全性

        ->insertGetId($data);//插入返回ID 第一步 插入  第二步 返回主键ID

    }

 

    /**

     * 多条插入

     */

    public function insertAll(){

        $data=[

            [

                'title'=>'新数据2',

                'code'=>'xsj2',

                'account_fields'=>'代付需要的数据2'

            ],

            [

                'title'=>'新数据3',

                'code'=>'xsj3',

                'account_fields'=>'代付需要的数据3'

            ]

        ];

        return Db::table('cash_channel')->insertAll($data);

 

    }

 

    /**

     * 更新

     */

    public function update(){

        //更新操作必须有条件,否则拒绝执行

        return Db::table('cash_channel')

        ->where('id',5)

        ->update(['title'=>'更新的数据title']);

        //如果更新条件是主键,那么可直接把主键写到更新的数组中

    }

 

    /**

     * 删除操作

     */

 

     public function delete(){

         return Db::table('cash_channel')

         ->delete(6);

     }

 

     /**

      * 原生查询 

      */

      public function query(){

          $sql='select * from cash_channel;';

          dump(Db::query($sql));

      }

 

      /**

       * 原生更新 删除 添加

       */

      public function execute(){

        //  return  Db::execute("update `cash_channel` set `title`='武松' where `id`=4");

         return Db::execute("insert `cash_channel` set `title`='ss';");

        //  return Db::execute("delete from `cash_channel` where `name`='ss'");

      }

 

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值