Connecting to Multiple Databases and Performing Cross‑Database Queries in ThinkPHP
This tutorial demonstrates how to use ThinkPHP's Db::connect() method and configuration files to establish multiple database connections, and shows two approaches for executing cross‑database queries either via fully qualified SQL statements or by iterating results between databases.
This article explains how to connect to multiple databases in ThinkPHP and perform cross‑database queries.
Method 1: Call Db::connect() with either a DSN string or a configuration array. Example:
Db::connect('mysql://root:[email protected]:3306/thinkphp#utf8'); Db::connect([
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'thinkphp',
'username' => 'root',
'password' => '',
'hostport' => '',
'charset' => 'utf8',
'prefix' => 'think_'
]);For detailed usage, refer to the ThinkPHP5 manual.
Method 2: Add multiple database configurations in the application config file, e.g., 'database1' => [...] and 'database2' => [...]. Connect by name with Db::connect('database1') and then use the returned instance for queries:
$db = Db::connect('database1');
$db->name('table')->select();Cross‑database query – Method 1: Use Db::query() with fully qualified table names ( database.table) in raw SQL, for example:
select * from database1.table1 as t1 inner join database2.table2 as t2 where t1.id = t2.id;Cross‑database query – Method 2: Query one database, iterate over the result set, and for each row query the second database, then combine the data as needed.
For more information, see the ThinkPHP5 complete development manual at https://www.kancloud.cn/manual/thinkphp5/118059 .
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
