thinkPHP5 Framework Realizes Multi database Connection Query Operation Example of Cross data Connection
- 2021-12-11 17:27:23
- OfStack
This article describes the example of thinkPHP5 framework to achieve multi-database connection, cross-data connection query operations. Share it for your reference, as follows:
1. Multidatabase connectivity
Method 1: Where you need to connect to other databases, use the
Db::connect()
Method dynamically connects to the database, and the method parameters are arrays or strings configured by the database, such as:
String parameters:
Db::connect('mysql://root:1234@127.0.0.1:3306/thinkphp#utf8');
Configure array parameters:
Db::connect([
// Database type
'type' => 'mysql',
// Database connection DSN Configure
'dsn' => '',
// Server address
'hostname' => '127.0.0.1',
// Database name
'database' => 'thinkphp',
// Database user name
'username' => 'root',
// Database password
'password' => '',
// Database connection port
'hostport' => '',
// Database connection parameters
'params' => [],
// Database encoding is adopted by default utf8
'charset' => 'utf8',
// Database table prefix
'prefix' => 'think_',
]);
For detailed usage, please refer to thinkphp5 Full Development Manual: https://www.kancloud.cn/manual/thinkphp5/118059
Method 2: Add multiple database configurations to the application configuration file, such as:
'database1' => []// Database configuration array
'database2' => []// Database configuration array
When a connection is required, use the
Db::connect("database1")
Connect to the specified database, and write functions directly after the connection when performing database operations, such as:
$db = Db::connect("database1");
$db->name("table")->select();
2. Query across database connections
Method 1: Use
Db::query("sql")
Method executes the sql statement, which is used in the sql statement
database.table
Specify databases and tables, such as:
Join queries the data of table table1 in database database1 and id in table table2 in database database2
select * from database1.table1 as t1 inner join database2.table2 as t2 where t1,id=t2.id
Method 2: Query different databases by loop
Now query data in database1, traverse the query result set, and query the data meeting the conditions in database2 respectively for splicing
ps: Please ask questions if the description is not in place
For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".
I hope this article is helpful to the PHP programming based on ThinkPHP framework.