博客列表 >5月23作业(tp数据库增删改查)

5月23作业(tp数据库增删改查)

张凯的博客
张凯的博客原创
2018年05月24日 17:27:24453浏览
<?php

/
 * @Author: zhangkai
 * @Date:   2018-05-24 15:09:47
 * @Last Modified by:   zhangkai
 * @Last Modified time: 2018-05-24 17:11:43
 */
namespace app\index\controller;
use think\Db;

class Query{
    // 1单记录查询
    public function find(){
        // 读操作返回的都是二维数组,没有满足条件的记录返回空数组
        // 写操作返回受影响的条数,没有返回0

        // 1查询方法table
        // $res = Db::table('staff')->find(10);
        $res = Db::table('staff')
            // ->field('name,sex,salary')
        ->field(["name"=>"姓名","sex"=>"性别","salary"=>"工资"])
            ->where('staff_id','=',11) //where(字段,表达式,条件)
            ->find();
        dump($res);
        // return "haha";
    }
    // 多条记录查询
    public function select(){
        $res = Db::table('staff')
            ->field(["name"=>"姓名","sex"=>"性别","salary"=>"工资"])
            ->where('salary>=8500')
            ->order('salary DESC')
            ->limit('2')
            ->select();
        dump($res);
    }
    // 添加记录
    public function insert(){
        // $data = [
        //     "name"=>"飞飞1",
        //     "sex"=>0,
        //     "age" => 18,
        //     "salary" => 3500
        // ];
        // $num = Db::table('staff')
        //     ->insert($data);
        // $id = Db::getLastInsID();

        // data将处理的数据打包 $option[]
        // insertGetId == insert + getLastInsID
        // $id = Db::table('staff')->insertGetId($data);
        // return ($num>=1) ? "插入成功 id".$id : "插入失败";
        // 多条记录插入
        $data = [
            ['name'=>'张三','sex'=>0,'salary'=>1000],
            ['name'=>'李四','sex'=>0,'salary'=>2000],
            ['name'=>'王五','sex'=>0,'salary'=>3000]
        ];
        $num = Db::table('staff')->data($data)->insertAll();
        return $num>=3 ? "插入成功 有".$num : "插入失败";

    }
    // 更新数据
    public function update(){
        $num = Db::table('staff')
            ->where('salary <= 4000')
            ->data(['salary'=>Db::raw('salary+500')])
            ->update();
            // ->update(['sex'=>1,'staff_id'=>19]);

        // dump($res);
        return $num ? "数据更新成功 有" .$num."条记录" : "更新失败";
    }
    // 删除
    public function delete(){
        // 删除基于前置查询,不允许无条件删除
        $num = Db::table('staff')->delete(34);
        // 清空表
        // $num = Db::table('staff')->delete(true);
        return $num ? "删除成功" : "删除失败";
    }

}


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议