Blogger Information
Blog 9
fans 0
comment 0
visits 5000
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月23作业(tp数据库增删改查)
张凯的博客
Original
465 people have browsed it
<?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 ? "删除成功" : "删除失败";
    }

}


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post