ThinkPHP6 connect to use the database, add, delete, modify, find, select, save, insert, insertAll, insertGetId, delete, update method usage

ThinkPHP6 connection using database

If the application needs to use the database, the database connection information must be configured. There are many ways to define the database configuration file.

Configuration file database.php

database.phpConfigure the following database parameters in the global or application configuration directory (config) (hereinafter collectively referred to as database configuration files):

return [
    'default'    =>    'mysql',
    'connections'    =>    [
        'mysql'    =>    [
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '127.0.0.1',
            // 数据库名
            'database'    => 'thinkphp',
            // 数据库用户名
            'username'    => 'root',
            // 数据库密码
            'password'    => '',
            // 数据库连接端口
            'hostport'    => '',
            // 数据库连接参数
            'params'      => [],
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => 'think_',
        ],
    ],
];

insert image description here

The new version is configured in a multi-type way, which is convenient for switching databases.

defaultConfiguration is used to set the database connection configuration used by default.
connectionsTo configure specific database connection information, defaultthe connection configuration defined by the configuration parameters must exist.

typeParameters are used to specify the database type

type database
mysql MySQL
sqlite SqLite
pgsql PostgreSQL
sqlsrv SqlServer
mongo MongoDb
oracle Oracle

Each application can set independent database connection parameters, usually just change defaultthe parameters directly:

return [
    'default'    =>    'admin', 
];

Toggle connection Db::connect

We can define multiple connection information in the database configuration file

return [
    'default'    =>    'mysql',
    'connections'    =>    [
        'mysql'    =>    [
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '127.0.0.1',
            // 数据库名
            'database'    => 'thinkphp',
            // 数据库用户名
            'username'    => 'root',
            // 数据库密码
            'password'    => '',
            // 数据库连接端口
            'hostport'    => '',
            // 数据库连接参数
            'params'      => [],
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => 'think_',
        ],
        'demo'    =>    [
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '127.0.0.1',
            // 数据库名
            'database'    => 'demo',
            // 数据库用户名
            'username'    => 'root',
            // 数据库密码
            'password'    => '',
            // 数据库连接端口
            'hostport'    => '',
            // 数据库连接参数
            'params'      => [],
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => 'think_',
        ],
    ],
];

We can call Db::connectmethods to dynamically configure database connection information, for example:

\think\facade\Db::connect('demo')
	->table('user')
    ->find();

connectThe method must be called at the beginning of the query, and the query method must be called immediately, otherwise it may cause some queries to fail or the default database connection will still be used.

The method of dynamically connecting to the database connectis only valid for the current query.

This method is more convenient to dynamically connect and switch databases, and is often used in the application requirements of multi-database connections.

Using native Mysql in tp6 - a small example

The native Mysql is the query method and the excute method.

The query method is used to perform MySql query operations

public function index(){
    
    
    $query = Db::query("select * from `book`");
    // 输出查询出的结果集数组
    dump($query);
}

The execute method is used to perform new and modified operations of MySql

public function index(){
    
    
    $execute = Db::execute("insert into `book` values(0,'大话数据结构','40','大牛')");
    // 输出查询出的结果集数组
    dump($execute);
}

Example: Query all information of a table and return

For simplicity, we directly call the query statement in the controller, and then return the result as a string to view.

insert image description here

First, configure the config/database.php database configuration file

<?php

return [
    // 默认使用的数据库连接配置
    'default'         => env('database.driver', 'mysql'),

    // 自定义时间查询规则
    'time_query_rule' => [],

    // 自动写入时间戳字段
    // true为自动识别类型 false关闭
    // 字符串则明确指定时间字段类型 支持 int timestamp datetime date
    'auto_timestamp'  => true,

    // 时间字段取出后的默认时间格式
    'datetime_format' => 'Y-m-d H:i:s',

    // 时间字段配置 配置格式:create_time,update_time
    'datetime_field'  => '',

    // 数据库连接配置信息
    'connections'     => [
        'mysql' => [
            // 数据库类型
            'type'            => env('database.type', 'mysql'),
            // 服务器地址
            'hostname'        => env('database.hostname', '127.0.0.1'),
            // 数据库名 自己的
            'database'        => env('database.database', 'phpdemo'),
            // 用户名
            'username'        => env('database.username', 'root'),
            // 密码 自己的密码
            'password'        => env('database.password', 'root'),
            // 端口
            'hostport'        => env('database.hostport', '3306'),
            // 数据库连接参数
            'params'          => [],
            // 数据库编码默认采用utf8
            'charset'         => env('database.charset', 'utf8'),
            // 数据库表前缀
            'prefix'          => env('database.prefix', ''),

            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'          => 0,
            // 数据库读写是否分离 主从式有效
            'rw_separate'     => false,
            // 读写分离后 主服务器数量
            'master_num'      => 1,
            // 指定从服务器序号
            'slave_no'        => '',
            // 是否严格检查字段是否存在
            'fields_strict'   => true,
            // 是否需要断线重连
            'break_reconnect' => false,
            // 监听SQL
            'trigger_sql'     => env('app_debug', true),
            // 开启字段缓存
            'fields_cache'    => false,
        ],

        // 更多的数据库配置信息
    ],
];

Then configure the controller:

<?php
namespace app\controller;

use app\BaseController;
use think\facade\View; // 使用模板引擎
use think\facade\Db; // 使用Db数据

class Index extends BaseController
{
    
    
    public function index()
    {
    
    
        $query = Db::query('select * from book');
        dump($query) ;
    }

}

It should be noted that in order to operate the database, the corresponding class must be imported use think\facade\Db. The dump() function here is actually almost the same as var_dump(), outputting the data type, data length and content.

insert image description here

Of course, we can also return the data to the front-end page and render it

Modify the controller code as follows:

<?php
namespace app\controller;

use app\BaseController;
use think\facade\View; // 使用模板引擎
use think\facade\Db; // 使用Db数据

class Index extends BaseController
{
    
    
    public function index()
    {
    
    
        $query = Db::query('select * from book');
        view::assign('books',$query);
        return view::fetch();
    }
   
}

Add view layer view/index/index.html

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table>
        <tr>
            <td>id</td>
            <td>书名</td>
            <td>价格</td>
            <td>作者</td>
        </tr>
        {foreach $books as $key=>$book}
        <tr>
            <td>{$book['id']}</td>
            <td>{$book['bookName']}</td>
            <td>{$book['bookPrice']}</td>
            <td>{$book['author']}</td>
        </tr>
        {/foreach}
    </table>
</body>
</html>

Visit to test whether rendering is successful:

insert image description here

Use the MySql provided by the framework

ThinkPHP6 provides a very rich query builder , which includes the following :

Query data, add data, update data, delete data, query expression, chain operation, aggregate query, pagination query, time query, advanced query, view query, JSON field, subquery, native query, get query parameters.

Only record the simplest crud operation...

1. Query data find select

1.1 Query a single data find

Query a single data using findmethod:

// table方法必须指定完整的数据表名
Db::table('think_user')->where('id', 1)->find();

The final generated SQL statement is:

SELECT * FROM `think_user` WHERE  `id` = 1 LIMIT 1

findThe method query result does not exist, return null, otherwise return the result array

1.2 query data set select

How to query multiple data (datasets) select:

Db::table('think_user')->where('status', 1)->select();

The final generated SQL statement is:

SELECT * FROM `think_user` WHERE `status` = 1

selectThe method query result is a dataset object, if you need to convert it to an array, you can use

Db::table('think_user')->where('status', 1)->select()->toArray();

The framework query operation provided by tp6 is similar to a chain operation. First specify the table name, then specify the condition, and finally perform the query (use find or select for a single data result set, and select for multiple data result sets).

2. Add data save insertAll insertGetId

2.1 Add a data save

You can use savethe method to uniformly write data, and automatically judge whether to add or update data (based on whether the primary key data exists in the written data).

$data = ['foo' => 'bar', 'bar' => 'foo'];
Db::name('user')->save($data);

Or use insertthe method to submit data to the database

$data = ['foo' => 'bar', 'bar' => 'foo'];
Db::name('user')->insert($data);

insertThe method adds data successfully and returns the number of successfully added items, usually returns 1

fooIf there is no or field in your data table bar, an exception will be thrown.

2.2 Add multiple data insertAll

To add multiple pieces of data, you can directly pass in the data to be added (usually a two-dimensional array) to insertAllthe method .

$data = [
    ['foo' => 'bar', 'bar' => 'foo'],
    ['foo' => 'bar1', 'bar' => 'foo1'],
    ['foo' => 'bar2', 'bar' => 'foo2']
];
Db::name('user')->insertAll($data);

insertAllThe method adds data successfully and returns the number of successfully added items

2.3 Add data and return the auto-increment primary key insertGetId

After adding data, if you need to return the auto-increment primary key of the newly added data, you can use insertGetIdthe method to add data and return the primary key value:

$data = [
    ['foo' => 'bar', 'bar' => 'foo'],
    ['foo' => 'bar1', 'bar' => 'foo1'],
    ['foo' => 'bar2', 'bar' => 'foo2']
];
$userId = Db::name('user')->insertGetId($data);

insertGetIdThe method adds data successfully and returns the auto-increment primary key of the added data

3. Delete data delete

// 根据主键删除
Db::table('think_user')->delete(1);
Db::table('think_user')->delete([1,2,3]);

// 条件删除    
Db::table('think_user')->where('id',1)->delete();
Db::table('think_user')->where('id','<',10)->delete();

The final generated SQL statement is:

DELETE FROM `think_user` WHERE  `id` = 1 
DELETE FROM `think_user` WHERE  `id` IN (1,2,3) 
DELETE FROM `think_user` WHERE  `id` = 1 
DELETE FROM `think_user` WHERE  `id` < 10

deleteThe method returns the number of affected data, and returns 0 if not deleted

4. Update data save update

4.1 save

Use the save method to update data

Db::name('user')->save(['id' => 1, 'name' => 'thinkphp']);

The actual generated SQL statement is:

UPDATE `think_user`  SET `name`='thinkphp'  WHERE  `id` = 1

4.2 update

updateThe method returns the number of affected data, and returns 0 if no data is modified.

How to use update.

Db::name('user')
    ->where('id', 1)
    ->update(['name' => 'thinkphp']);

The actual generated SQL statement is:

UPDATE `think_user`  SET `name`='thinkphp'  WHERE  `id` = 1

summary

To use the tp6 framework to manipulate the database, you must first modify the database configuration file ( config/database.php). After the configuration is complete, you can operate the database.

Then remember to import the module when using it use think\facade\Db; , and then you can use the methods in the tp6 data constructor.

find You can use or to query a single data select, but you can only use the method to query multiple data select .

Adding a single data can be used save, adding multiple pieces of data can be used insertAll , you can use insertGetIdthe method to add new data and return the primary key value.

Delete data can be used delete, update data can be used saveor update.

Methods in tp6's data constructor can be used like a chain...

Guess you like

Origin blog.csdn.net/m0_63622279/article/details/130669623