博客列表 >5.23 thinkPHP5中数据库操作

5.23 thinkPHP5中数据库操作

吃不起土的少年的博客
吃不起土的少年的博客原创
2018年05月29日 17:01:21735浏览

实例

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

class Query{
  public function find(){
    $res =Db::table('staff')
         ->where('staff_id','10')
         ->find();
// 指定字段查询
         // $res = Db::table('staff')
         // 			->field(['name'=>'姓名','sex'=>'性别','age'=>'年龄'])
         // 			->where('staff_id',11)
         // 			->find();
         dump($res);

  }
  //多条查询
  public function select()
  {
    $res=Db::table('staff')
       ->field(['name'=>'姓名','salary'=>'工资'])
       ->where('salary','<','10000')
       ->order('salary','DESC')
       ->limit(3)
       ->select();
       dump($res);
  }
  //新增数据
  public function insert(){

    // 将新增的数据打包的一个关联数组中
    $data=[
      'name'=>'德洛斯',
      'sex'=>0,
      'age'=>60,
      'salary'=>5789
    ];
    $num=Db::table('staff')->data($data)->insert();
    $id=Db::getLastInsID();
    return $num?'添加成功,id='.$id :'没有数据被添加';
    //多条数据新增
    $data=[
      ['name'=>'威廉','sex'=>0,'age'=>24,'salary'=>2938],
      ['name'=>'佛特','sex'=>0,'age'=>54,'salary'=>10548],
      ['name'=>'梅芙','sex'=>1,'age'=>28,'salary'=>3358]
    ];

    $num=Db::table('staff')->data($data)->insertALL();

    return $num?'添加成功'.$num.'条数据' :'没有数据被添加';
  }
  //更新操作
  public function update()
  {
    $num = Db::table('staff')
         ->where('staff_id','=','10')
         ->data(['salary'=>Db::raw('salary+4000')])
         ->update();

      $num = Db::table('staff')
          ->update(['sex'=>0,'staff_id'=>10]);
         return $num ? '更新成功'.$num.'条记录~~' : '没有记录被更新';
  }
  //删除操作
  public function delete(){
    $num = Db::table('staff')
         ->where('staff_id','=','1')
         ->delete();
         return $num ? '删除成功'.$num.'条数据' : '没有数据被删除';
  }
}

 ?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


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