1. Design the database table
For example, I created a new database table named test
Second, configure the database connection information
-
local test
Modify directly in .env instead of modifying in config/database.php
-
Formal environment
Three, add, delete, modify and check
-
Import Db library
use think\facade\Db;
Suppose the newly added controller path is
app\test\controller\CURD.php
2. increase
// 增
public function insert()
{
$data = ['name' => 'lili', 'age' => 18];
$result = Db::name('test')->insert($data);
var_dump($result);
}
Db::name('test') where 'test' is the name of the database table, using the insert operation, returns the number of successfully inserted items, usually returns 1
3. Check
// 查
public function select()
{
// 查所有
$result = Db::name('test')->select()->toArray();
print_r($result);
print_r('<br/>');
print_r('<br/>');
// 查一个 (多个条件用多个where)
$result = Db::name('test')->where('name', 'lili')
->where('age', '>', 3)->select()->toArray();
var_dump($result);
}
-
The query uses select(), which returns an object, so use ->toArray() to convert it into an array
-
The query condition uses where('field name','query expression','query condition'), and the default 'query expression' means equal to
-
Multiple where can be connected
4. change
// 改
public function update()
{
$result = Db::name('test')->where('name', 'lili')
->update(['age' => 20]);
var_dump($result);
}
Use update to return the number of affected data, and return 0 if no data has been modified
5. delete
// 删
public function delete()
{
$result = Db::name('test')->where('name', 'lili')->delete();
var_dump($result);
}
Use delete to return the number of items that affect the data, and return 0 if not deleted
4. Detailed tutorial
https://www.kancloud.cn/manual/thinkphp6_0/1037533
Software engineering classmate Xiao Shi
2023.08.30