批改状态:合格
老师批语:
<?php
namespace app\index\controller;
use think\Db;
class Query
{
public function find()
{
$res = Db::table('staff')
->find(10);
$res = Db::table('staff')
->where('staff_id',11)
->find();
//如果要指定查询的字段使用field()方法
$res = Db::table('staff')
->field(['name'=>'姓名','sex'=>'性别','age'=>'年龄']) //可设置字段别名
->where('staff_id',11)
->find();
dump($res);
}
public function select()
{
//查询满足条件的多条记录select()
$res = Db::table('staff')
->field(['name'=>'姓名','salary'=>'工资'])
->where('salary','>',3000)
->order('salary','DESC')
->limit(5)
->select();
dump($res);
}
public function insert()
{
$data = [
'name' => '胡一刀',
'sex' => 0,
'age' => 49,
'salary' => 5300
];
$id = Db::table('staff')->insertGetId($data);
return $id ? '添加成功,id='.$id : '没有记录被添加';
//新增多条记录 insertAll()
$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();
return $num ? '添加成功'.$num.'条记录~~' : '没有记录被添加';
}
public function update()
{
$num = Db::table('staff')
->where('salary','<=',4000)
->data(['salary'=> Db::raw('salary+1000')])
->update();
$num = Db::table('staff')
//如果更新记录中存在主键,则直接根据主键更新
->update(['sex'=>1,'staff_id'=>19]);
return $num ? '更新成功'.$num.'条记录~~' : '没有记录被更新';
}
public function delete()
{
$num = Db::table('staff')->where('salary','>',10000)->delete();
$num = Db::table('staff')->delete(true); //数据表后面还要用,此功能课后练习
return $num ? '删除成功'.$num.'条记录~~' : '没有记录被删除';
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号