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:
The Solution:
To perform cross database queries in PHP without excessive modifications, the following steps can be taken:
$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中文網其他相關文章!