Wednesday, January 12, 2011

Connecting two mysql tables from different databases - PHP answers

This site have interesting examples to connect 2 MySQL tables in different database on different servers
Connecting two mysql tables from different databases - PHP answers

  1. //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.
  2. //MySQL Server 1
  3. $dbhost1 = "127.0.0.1";
  4. $dbuser1 = "dbuser1";
  5. $dbpassword1 = "dbpass1";
  6. $db1 = "database1";
  7. $connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
  8. mysql_select_db($db1,$connection1);
  9. //MySQL Server 2
  10. $dbhost2 = "xxx.xxx.xxx.xxx";
  11. $dbuser2 = "dbuser2";
  12. $dbpassword2 = "dbpass2";
  13. $db2 = "database2";
  14. $connection2 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
  15. mysql_select_db($db2,$connection2);
  16. //The SQL statement
  17. $sql =" SELECT database1.tablename1.fieldname1 AS field1, database2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tablename2";
  18. //Execute query and collect results in $results
  19. $results = mysql_query($sql);
  20. //Print result until end of records
  21. while($rows = mysql_fetch_array($results)){
  22. print $rows["field1"]." | ".$rows["field2"]."
    ";
  23. }
  24. ?>

No comments:

Post a Comment