The following tutorial column will introduce you to the ThinkPHP database operation and connecting to the database. I hope it will be helpful to friends in need! ThinkPHP has a built-in abstract database access layer, which encapsulates different database operations. We only need to use the public Db class to operate without writing different codes and underlying implementations for different databases. The Db class will automatically call the corresponding database driver for processing. Using PDO method, it currently includes support for Mysql, SqlServer, PgSQL, Sqlite and other databases.
If the application needs to use a database, the database connection information must be configured. There are many ways to define the database configuration file.
1. Configuration file definition2. Method configuration- 3. Model class definition
- Configuration parameter reference
- 1. Configuration file definition
The common configuration method is to add the following configuration parameters in database.php under the application directory or module directory:return [
// 数据库类型 'type' => 'mysql',
// 数据库连接DSN配置 'dsn' => '',
// 服务器地址 'hostname' => '127.0.0.1',
// 数据库名 'database' => 'thinkphp',
// 数据库用户名 'username' => 'root',
// 数据库密码 'password' => '',
// 数据库连接端口 'hostport' => '',
// 数据库连接参数 'params' => [],
// 数据库编码默认采用utf8 'charset' => 'utf8',
// 数据库表前缀 'prefix' => 'think_',
// 数据库调试模式 'debug' => false,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'deploy' => 0,
// 数据库读写是否分离 主从式有效 'rw_separate' => false,
// 读写分离后 主服务器数量 'master_num' => 1,
// 指定从服务器序号 'slave_no' => '',
// 是否严格检查字段是否存在 'fields_strict' => true,];
The type parameter supports the complete definition of the namespace. If there is no namespace definition, \think\db\connector is used as the namespace by default. If you use the database driver that applies your own extension, it can be configured as:
// 数据库类型 'type' => '\org\db\Mysql',
Indicates that the database connector uses the \org\db\Mysql class as the database connection driver instead of the default \think\db\connector\Mysql.
Each module can set independent database connection parameters, and the same configuration parameters do not need to be set repeatedly. For example, we can define it in the database.php configuration file of the admin module:return [ // 服务器地址 'hostname' => '192.168.1.100', // 数据库名 'database' => 'admin',];
means that the database address of the admin module is changed to 192.168.1.100, the database name is changed to admin, and other connection parameters are the same as the configuration in the application's database.php. Starting from V5.0.6, Mysql’s disconnection and reconnection mechanism is supported. It is turned off by default. If necessary, add:
// 开启断线重连 'break_reconnect' => true,
to the database configuration file. Connection parameters
You can add database connection parameters for different connection needs (for specific connection parameters, please refer to the PHP manual). The built-in parameters include the following: PDO::ATTR_CASE => PDO::CASE_NATURAL,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,PDO::ATTR_STRINGIFY_FETCHES => false,PDO::ATTR_EMULATE_PREPARES => false,
The connection configuration in the params parameter set in the database will be merged with the built-in setting parameters. If you need to use a long connection and return the lowercase column name of the database, you can define it in the following way:
'params' => [ \PDO::ATTR_PERSISTENT => true, \PDO::ATTR_CASE => \PDO::CASE_LOWER,],You can configure any connection parameters supported by PDO in params.
2. Method configuration
We can dynamically define the connection information when calling the Db class, for example: Db::connect([ // 数据库类型
'type' => 'mysql', // 数据库连接DSN配置
'dsn' => '', // 服务器地址
'hostname' => '127.0.0.1', // 数据库名
'database' => 'thinkphp', // 数据库用户名
'username' => 'root', // 数据库密码
'password' => '', // 数据库连接端口
'hostport' => '', // 数据库连接参数
'params' => [], // 数据库编码默认采用utf8
'charset' => 'utf8', // 数据库表前缀
'prefix' => 'think_',]);
Or use string mode:
Db::connect('mysql://root:1234@127.0.0.1:3306/thinkphp#utf8');
The definition format of string connection is:
Database type://username:password@database Address: Database port/database name#Character set
Note: String mode may not be able to define some parameters, such as prefix and connection parameters.
If we have configured additional database connection information in the application configuration file
//数据库配置1
'db_config1' => [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'thinkphp',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'think_',],
//数据库配置2
'db_config2' => 'mysql://root:1234@localhost:3306/thinkphp#utf8';
We can change it to
Db::connect('db_config1'); Db::connect('db_config2');
3. Model class definition
If in a certain model class If the connection attribute is defined in it, the model will automatically connect to the given database connection when operating, instead of the default connection information set in the configuration file. It is usually used for some data tables located in other databases outside the current database connection. For example: //在模型里单独设置数据库连接信息
namespace app\index\model;
use think\Model;class User extends Model
{ protected $connection = [ // 数据库类型
'type' => 'mysql', // 数据库连接DSN配置
'dsn' => '', // 服务器地址
'hostname' => '127.0.0.1', // 数据库名
'database' => 'thinkphp', // 数据库用户名
'username' => 'root', // 数据库密码
'password' => '', // 数据库连接端口
'hostport' => '', // 数据库连接参数
'params' => [], // 数据库编码默认采用utf8
'charset' => 'utf8', // 数据库表前缀
'prefix' => 'think_',
];
}
can also be defined in DSN string mode, for example:
//在模型里单独设置数据库连接信息 namespace app\index\model; use think\Model;class User extends Model { //或者使用字符串定义 protected $connection = 'mysql://root:1234@127.0.0.1:3306/thinkphp#utf8'; }
It should be noted that ThinkPHP’s database connection is lazy, so it is not The database is connected when instantiated, but will be connected to the database when there is actual data operation.
Configuration parameter reference
The following is the default supported database connection information:
Parameter name | Description | Default value |
type | Database type | None |
Database address | 127.0.0.1 | |
Database name | None | |
Database username | None | |
Database password | None | |
Database port number | None | ##dsn |
None | params | |
empty | charset | |
utf8 | prefix | |
None | debug | |
false | deploy | |
0 | rw_separate | |
false | master_num | |
1 | slave_no | |
None | ##fields_strict | |
true | resultset_type | |
array | ##auto_timestamp | Automatically write timestamp field |
sql_explain | Whether it is necessary to perform SQL performance analysis and enable debugging to be effective | |
query | Specify the query object | |
builder | Specify the database Builder object | |
##
If you are using the pgsql database driver, please first import the thinkphp/library/think/db/connector/pgsql.sql file into the database for execution.
The above is the detailed content of ThinkPHP database operation to connect to the database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software