涣顶拌叭浑獭船壳摩逻凤淘莆
delete(true)是无条件删除,即清空数据表,是非常危险的操作,需要慎重!!!
需要注意delete操作不支持闭包
1.新增操作:
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->insert([ 'name'=>'萌面人', 'sex'=>1, 'age'=>28 ]); return $affected ? "成功添加".$affected.'条数据':"添加失败"; } }
执行:
萌面人被插入数据表中
insertAll添加多条数据
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->insertAll([ ['name'=>"张无忌",'sex'=>1,'age'=>40], ['name'=>"赵敏",'sex'=>0,'age'=>30], ['name'=>"张三丰",'sex'=>1,'age'=>80] ]); return $affected ? "成功添加".$affected.'条数据':"添加失败"; } }
执行:
2.更新:更新必须提供更新条件,不允许无条件更新
数据表中完善数据
将id=13的张三丰的工资更新为3000
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->update(['id'=>13,'salary'=>3000]); return $affected ? "成功更新".$affected.'条数据':"更新失败"; } }
执行:
在where()中写更新条件
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->where('id=13') ->update(['salary'=>5000]); return $affected ? "成功更新".$affected.'条数据':"更新失败"; } }
执行:
自增操作
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->where('id=13') ->setInc('age',10);//年龄每次自增10 return $affected ? "成功更新".$affected.'条数据':"更新失败"; } }
执行:
自减操作
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->where('id=13') ->setDec('age',10);//年龄每次自减10 return $affected ? "成功更新".$affected.'条数据':"更新失败"; } }
执行:
自增,自减还支持延时更新,这样可以避免频繁的操作数据库
<?php namespace app\index\controller; use think\Db; class Index { public function index() { $affected=Db::table('staff') ->where('id',13) ->setDec('age',20,3);//年龄每次自减20,3秒后执行 return $affected ? "成功更新".$affected.'条数据':"更新失败"; } }
执行:
理论上三秒后年龄会变为60,然鹅并没有,不知道什么原因
镭葛耻挡抽蔚抄晶蛙楞遁畏肛