Databases 3 min read

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.

php Courses
php Courses
php Courses
Connecting to Multiple Databases and Performing Cross‑Database Queries in ThinkPHP

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 .

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ThinkPHPcross-databaseDb::connectmultiple-database
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.