Thinkphp6 Getting Started (4)--Addition, deletion, modification and query of database operations

1. Design the database table

For example, I created a new database table named test

picture

Second, configure the database connection information

  1.  local test

    Modify directly in .env instead of modifying in config/database.php

    picture

  2. Formal environment

    picture

Three, add, delete, modify and check

  1.  Import Db library

use think\facade\Db;

Suppose the newly added controller path is

app\test\controller\CURD.php

picture

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

picture

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

picture

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

picture

picture

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

picture

picture

4. Detailed tutorial

https://www.kancloud.cn/manual/thinkphp6_0/1037533

Software engineering classmate Xiao Shi 

2023.08.30

Guess you like

Origin blog.csdn.net/u013288190/article/details/132679152