Connecting two mysql tables from different databases - PHP answers
- //Define your database connections and select your database want to use. In this example I use two connections and two DBs. But you can use more than two.
- //MySQL Server 1
- $dbhost1 = "127.0.0.1";
- $dbuser1 = "dbuser1";
- $dbpassword1 = "dbpass1";
- $db1 = "database1";
- $connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
- mysql_select_db($db1,$connection1);
- //MySQL Server 2
- $dbhost2 = "xxx.xxx.xxx.xxx";
- $dbuser2 = "dbuser2";
- $dbpassword2 = "dbpass2";
- $db2 = "database2";
- $connection2 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
- mysql_select_db($db2,$connection2);
- //The SQL statement
- $sql =" SELECT database1.tablename1.fieldname1 AS field1, database2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tablename2";
- //Execute query and collect results in $results
- $results = mysql_query($sql);
- //Print result until end of records
- while($rows = mysql_fetch_array($results)){
- print $rows["field1"]." | ".$rows["field2"]."
"; - }
- ?>