批改状态:合格
老师批语:
<?php
namespace app\index\controller;
use think\Db;
class Query
{
public function find()
{
//find方法参数主键查询,取出一条数据
$res = Db::table('staff')
->find(10);
$res = Db::table('staff')
->where('staff_id',1)
->find();
//field选择查询的数据库字段
$res = Db::table('staff')
->field(['name'=>'姓名','sex'=>'性别','age'=>'年龄'])
->where('staff_id',1)
->find();
dump($res);
}
public function select()
{
//select查询多条记录
//order按条件排序
//limit取出数据数量
$res = Db::table('staff')
->field(['name'=>'姓名','salary'=>'工资'])
->where('salary','>',3000)
->order('salary','DESC')
->limit(5)
->select();
dump($res);
}
public function insert()
{
//insert新增一条数据
$data = [
'name' => '张三',
'sex' => 0,
'age' => 16,
'salary' => 5100
];
$num = Db::table('staff')->insert($data);
$id = Db::getLastInsID();
return $id ? '添加成功,id='.$id : '没有记录被添加';
$num = Db::table('staff')->data($data)->insert();
$id = Db::getLastInsID();
return $num ? '添加成功,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()
{
//update更新
$num = Db::table('staff')
->where('salary','<=',4000)
//Db::raw()引用原salary字段的值
->data(['salary'=> Db::raw('salary+1000')])
->update();
$num = Db::table('staff')
->update(['sex'=>1,'staff_id'=>19]);
return $num ? '更新'.$num.'条记录' : '没有记录被更新';
}
public function delete()
{
//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号