首頁 >資料庫 >mysql教程 >如何在PHP中執行跨資料庫查詢?

如何在PHP中執行跨資料庫查詢?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 07:04:02451瀏覽

How to Perform Cross Database Queries in PHP?

Cross Database Queries in PHP

In a previous discussion, cross database queries in MySQL were addressed. However, when attempting to implement this knowledge in PHP, challenges arose.

The Problem:

PHP offers two approaches using mysql_select_db:

  1. Using mysql_select_db restricts access to a single database at a time.
  2. Omitting mysql_select_db requires specifying the database with each query, which is inconvenient and impractical.

The Solution:

To perform cross database queries in PHP without excessive modifications, the following steps can be taken:

  1. Ensure that the databases reside on the same host.
  2. Establish a connection to the preferred database using mysql_select_db.
  3. Manually specify the foreign database in the query, as seen below:
$db = mysql_connect($host, $user, $password);
mysql_select_db('my_most_used_db', $db);

$q = mysql_query("
    SELECT *
    FROM   table_on_default_db a, `another_db`.`table_on_another_db` b
    WHERE  a.id = b.fk_id
");

If the databases are on different hosts, direct joins are not possible. In that case, two queries can be performed instead:

$db1 = mysql_connect($host1, $user1, $password1);
$db2 = mysql_connect($host2, $user2, $password2);

$q1 = mysql_query("
    SELECT id
    FROM   table
    WHERE  [..your criteria for db1 here..]
", $db1);
$tmp = array();
while($val = mysql_fetch_array($q1))
    $tmp[] = $val['id'];

$q2 = mysql_query("
    SELECT *
    FROM   table2
    WHERE  fk_id in (".implode(', ', $tmp).")
", $db2);

以上是如何在PHP中執行跨資料庫查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn