Working With Multiple Databases
Working With Multiple Databases
php
$conn = mysql_connect("localhost", "root", "");
$db1 = mysql_select_db("database1", $conn);
$db2 = mysql_select_db("database2", $conn);
1. php
2.
3. //Define your database connections and select your database want t
o use. In this example I use two connections and two DBs. But you can use
more than two.
4.
5. //MySQL Server 1
6. $dbhost1 = "127.0.0.1";
7. $dbuser1 = "dbuser1";
8. $dbpassword1 = "dbpass1";
9. $db1 = "database1";
10. $connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or di
e (mysql_error());
11. mysql_select_db($db1,$connection1);
12.
13. //MySQL Server 2
14. $dbhost2 = "xxx.xxx.xxx.xxx";
15. $dbuser2 = "dbuser2";
16. $dbpassword2 = "dbpass2";
17. $db2 = "database2";
18. $connection2 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or di
e (mysql_error());
19. mysql_select_db($db2,$connection2);
20.
21. //The SQL statement
22. $sql =" SELECT database1.tablename1.fieldname1 AS field1, database
2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tab
lename2";
23.
24. //Execute query and collect results in $results
25. $results = mysql_query($sql);
26.
27. //Print result until end of records
28. while($rows = mysql_fetch_array($results)){
29. print $rows["field1"]." | ".$rows["field2"]."<br>";
30. }
this script connects at two databases, each one located on a different server, and
clones the source_table from the second database to the destination_table located
on localhost (first database)
<?php
$host1="localhost"; // destination
$base1="first_database";
$user1="root";
$password1="";
$host2="192.168.0.1"; //source
$base2="second_database";
$user2="root";
$password2="xxx";
mysql_close($conection1);
mysql_close($conection2);
?>
It's really not difficult to join seperate databases (assuming they reside on the same server)
Just like you would specify fields using the "table.field", you can also use "database.table.field"
Below is an example of a two database join: