Home >PHP Framework >ThinkPHP >thinkPHP5 framework implements multiple database connections
The following is the thinkphp framework tutorial column to introduce the thinkPHP5 framework to implement multi-database connections and cross-data connection query operations. I hope it will be helpful to friends in need!
The details are as follows:
1. Multiple database connections
Method 1:When a connection is required For other databases, use the Db::connect()
method to dynamically connect to the database. The method parameters are arrays or strings configured in the database. For example:
String parameters:
Db::connect('mysql://root:1234@127.0.0.1:3306/thinkphp#utf8');
Configuration array parameters:
Db::connect([ // 数据库类型 'type' => 'mysql', // 数据库连接DSN配置 'dsn' => '', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'thinkphp', // 数据库用户名 'username' => 'root', // 数据库密码 'password' => '', // 数据库连接端口 'hostport' => '', // 数据库连接参数 'params' => [], // 数据库编码默认采用utf8 'charset' => 'utf8', // 数据库表前缀 'prefix' => 'think_', ]);
For detailed usage, please refer to thinkphp5 complete development manual: https://www.kancloud.cn/manual/thinkphp5/118059
Method 2: Add multiple database configurations in the application configuration file, for example:
'database1' => []//数据库配置数组 'database2' => []//数据库配置数组
When you need to connect, use Db::connect("database1")
to specify the connection Database, when performing database operations, write functions in a chain directly after the connection, for example:
$db = Db::connect("database1"); $db->name("table")->select();
2. Cross-database connection query
Method 1: Use the Db::query("sql")
method to execute the sql statement, and use database.table
in the sql statement to specify the database and table, for example :
Connect to query the data with the same ID in table1 in database database1 and table2 in database database2
select * from database1.table1 as t1 inner join database2.table2 as t2 where t1,id=t2.id
Method 2: Use loops to query different databases respectively
Now query the data in database1, traverse the query result set, and separately query the data that meets the conditions in database2 for splicing
ps: If the description is not in place, please ask questions
The above is the detailed content of thinkPHP5 framework implements multiple database connections. For more information, please follow other related articles on the PHP Chinese website!