一、DB类的新增操作,使用静态方法insert()与insertAll()
1、使用insert新增单条记录,代码如下:
<?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实现新增多条记录操作,代码如下:
$affected = Db: :table( 'staff' )
->insertAll( [
[ ' name '=> '张无忌',' sex'=>1, ' age'=>40] ,
[ ' name '=> '赵敏',' sex'=>0,' age '=>30] ,
['name'=> '张三丰','sex'=>1, 'age '=>80] ,
]);
二、DB类的更新操作,使用静态方法update()
<?php
namespace app\ index\controller;
use think\Db;
class Index
{
public function index( )
{
$affected = Db::table( 'staff' )
->where( ' id', 1023)
->update( [‘salary'=> 5000] );
return $affected ? '<h3> 成功更新了' . $affected. '条记录</h3>' : ' 更新失败;
}
}
自增更新setInc()与setDec(),第一个参数为更新字段,第二个参数为步长,第三个参数为时间延时。
public function index( )
{
$affected = Db: :table( 'staff')
->where( id',1023 )
->setInc( 'age' ,10,3) ;
return $affected ? '<h3> 成功更新了' .$affected. ' 条记录</h3>' : ' 更新失败
}
|