我创建的一张商品表

Original 2019-06-14 14:31:15 255
abstract:<?phpnamespace app\index\controller;use think\Db;class Demo5{//1、单条查询    public function find()    {$res = Db::table('mt_student')//           &

<?php
namespace app\index\controller;
use think\Db;

class Demo5
{
//1、单条查询
   public function find()
   {

$res = Db::table('mt_student')
//            -> field('id','name','email')
           ->where('id', '=', 2)
           ->find();

//        is_null($res) ? '没有找到' : '$res' 判断$res是否为空,为空,显示没有找到,非空,显示$res;
       dump(is_null($res) ? '没有找到' : '$res');

}



/*
    * 2、多条查询
    * */

   public function select()
   {
//        select()返回的是一个二维数组,没有数据返回一个空数据
       $res = Db::table('mt_student')
           -> field ('id,name,course,grade')
           -> where ([
               ['course','=','php'],
               ['grade','>=',80]
           ]) -> select();

       if(empty($res)){
           return '没有满足条件的记录';
       }else{
           foreach ($res as $row){
               dump($row);
           }
       }

   }



//    3、单条插入

   public function insert()
   {
//        insert()成功返回插入的数量,即新增的数量;失败返回false
//        准备一下要插入的数据,放在一个数组data中
       $data = [

           'name' => '洪七公3',
           'email' => '777@email.com',
           'course' => 'java',
           'grade' => '86'
       ];

//        return Db::table('mt_student')-> insert($data); //普通插入一条数据
//        return Db::table('mt_student')-> insert($data,true); //可以替换更新一条数据内容
//        return Db::table('mt_student') -> data($data) -> insert(); //data()方法可以做一些最基本的过滤


//        插入的同时返回新增主键ID
//        insertGetId()执行两步操作, 第一步插入数据,第二步返回新生的主键ID
       return Db::table('mt_student')-> insertGetId($data);



   }







//    4、多条插入
   public function insertAll()
   {
       $data = [
           ['name'=>'peter','email'=>'php@php.cn'],
           ['name'=>'jack','email'=>'j@php.cn'],
           ['name'=>'black','email'=>'b@php.cn'],
       ];

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

   }








//    5、更新操作:一定有更新条件;如果成功,返回更新成功,并显示更新x条;如果失败,显示false; 不支持 data()方法;
       public function update()
       {
//            return Db::table('mt_student')
//                -> where('id',4)
//                -> update(['name'=>'西门庆']);

//            如果更新条件是主键ID,可以简写
           return Db::table('mt_student')
               -> update(['id'=>'5','name'=>'小金莲']);
       }







//        6、删除操作
   public function delete()
   {
//        return Db::table('mt_student')
//            -> delete(11);

       return Db::table('mt_student')
           -> where('id',12)
           -> delete();
   }


Correcting teacher:天蓬老师Correction time:2019-06-14 15:06:37
Teacher's summary:->where('id', '=', 2), 相等操作时, 不需要添加等号, 请遵循代码规范

Release Notes

Popular Entries