php5.23升级,5.23 - php中文网作业 - php中文网博客

以实例演示:查询构造器中的10个最常用的方法

Table(),field(),order(),where(),limit(),insert(),insertAll(),update(),delete(),

以及如何获取自增主键和数据打包方法data()

以实例演示:查询构造器中的10个最常用的方法

Table(),field(),order(),where(),limit(),insert(),insertAll(),update(),delete(),

以及如何获取自增主键和数据打包方法data()

查询构造器中的10个最常用的方法

Table(),    内写需要查询的表名,本例中为staff

$res = Db::table('staff')

->field(['name'=>'姓名','sex'=>'性别','salary'=>'工资'])

->where('staff_id','>=',10)//where(字段,表达式,条件)

->find();

dump($res);

field(),    内写需要显示的列名,比如在本例中显示的是name,sex,salary,

limit(),

查询单条记录,方法名为find()

本例中的sql语句为:

SELECT `name` AS `姓名`,`sex` AS `性别`,`salary` AS `工资` FROM `staff` WHERE  `staff_id` >= 10 LIMIT 1

查询多条记录,方法名为select,

where()

内写条件表达式,给查询设置符合预期查询的条件

本例中,要求员工id>=10

order(),

内有两个参数,第一个是需要排序的列名,第二个是按照升序ASC

还是降序(DESC),

public function select()

{

//查询多条记录

$res = Db::table('staff')

->field(['name'=>'姓名','salary'=>'工资'])

->where('salary','>',3000)

->order('salary','DESC')

->limit(5)

->select();

dump($res);

}

insert(),    插入单条记录    public function insert()

{

//新增单条记录:insert()

$data = [

'name' =>'胡一',

'sex' => 0,

'age' => 49,

'salary' => 5300

];

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

//$id = Db::getLastInsID();

//return $num ? '添加成功,id='.$id :'没有记录被添加';

//data($data)将要处理的数据打包$option[]

//indertGetId() == insert() + getLastInsID()

$id = Db::table('staff')->insertGetId($data);

return $id ? '添加成功,id='.$id : '没有满足条件的记录';

}

insertAll(),    方法insertAll用于插入多条记录    //新增多条记录用:insert ALL()

$data = [

['name'=>'张飞','sex'=>0,'age'=>48,'salary'=>6900],

['name'=>'刘备','sex'=>0,'age'=>58,'salary'=>4500],

['name'=>'关羽','sex'=>0,'age'=>53,'salary'=>4700],

];

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

return $num ? '添加成功'.$num.'条记录~~' : '没有记录被添加被添加';

update(),      1.更新操作必须是基于前置查询,不允许无条件更新

2. 更新使用update,也是终极方法

public function update()

{

//将工资<=4000的员工,加薪1000

/* $num = Db::table('staff')

->where('salary','<=',5000)

->data(['salary'=> Db::raw('salary+1000')])

->update(); */

$num = Db::table('staff')

->update(['sex'=>0,'staff_id'=>18]);

return $num ? '更新成功'.$num.'条记录~~' : '没有记录被更新';

}

delete(),

//删除也必须基于前置查询,不允许无条件删除

//删除用delete方法

//$num = Db::table('staff')->delete(true);//清空表

public function delete()

{

$num = Db::table('staff')

->where('staff_id',16)

->delete();

return $num ? '删除成功'.$num.'条记录~~' : '没有记录被删除';

}

获取自增主键方法    数据打包方法

$id = Db::table('staff')->insertGetId($data);

data()

data($data)将要处理的数据打包$option[]

indertGetId() == insert() + getLastInsID()

$id = Db::table('staff')->insertGetId($data);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值