Home > PHP Framework > ThinkPHP > body text

ThinkPHP database operation to connect to the database

藏色散人
Release: 2021-01-25 09:01:17
forward
4055 people have browsed it

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 definition

2. 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,];
Copy after login
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',
Copy after login

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',];
Copy after login

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,
Copy after login

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,
Copy after login
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,],
Copy after login

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_',]);
Copy after login
Or use string mode:

Db::connect('mysql://root:1234@127.0.0.1:3306/thinkphp#utf8');
Copy after login

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

(note that this is not a database configuration file), for example:

//数据库配置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';
Copy after login
We can change it to

Db::connect('db_config1');
Db::connect('db_config2');
Copy after login


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_',
    ];
}
Copy after login
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';
}
Copy after login

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:

##hostnameDatabase address127.0.0.1databaseDatabase nameNone##usernamepasswordhostport##dsnDatabase connection dsn informationNoneparamsDatabase connection parametersemptycharsetDatabase encodingutf8prefixTable prefix of the databaseNonedebugWhether debug modefalsedeployDatabase deployment mode: 0 centralized (single server), 1 distributed ( Master-slave server)0rw_separateWhether the database reading and writing are separated in master-slave mode is validfalsemaster_numThe number of master servers after read and write separation1slave_noSpecify the slave Server serial numberNoneWhether to strictly check whether the field existsDataset return type##auto_timestampAutomatically write timestamp fieldfalsesql_explainWhether it is necessary to perform SQL performance analysis and enable debugging to be effectivefalse querySpecify the query objectthink\db\QuerybuilderSpecify the database Builder object NoneNote:
Parameter name Description Default value
type Database type None
Database username None
Database password None
Database port number None
##fields_strict
true resultset_type
array

## 

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template