ThinkPHP database operation to connect to the database
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,];
// 数据库类型 '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,
'params' => [ \PDO::ATTR_PERSISTENT => true, \PDO::ATTR_CASE => \PDO::CASE_LOWER,],
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_',]);
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';
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_',
];
}
//在模型里单独设置数据库连接信息 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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.
