How to connect to two databases simultaneously from 2 different server?

Stringx's Avatar, Join Date: Feb 2011
Newbie Member

How to connect to two databases simultaneously from 2 different server?

I have established a connection to db1, while on 'while loop' a certain field needs to access data from db2 from different server. How this would be implemented, using MySQL and PHP?

underground_devil's Avatar, Join Date: Jan 2011
Go4Expert Member
i never tried but i am sure u can do by using two connection files
ManzZup's Avatar, Join Date: May 2009
Skilled contributor
its easy i think
you should make two db handlers

PHP Code:
//your primary connection
$conn mysql_connect("host1","username","password");

//connect to your first db with first handle

$conn2 mysql_connect("host1","username","password",true); 
//should put that true to make a new connection

   //connect to your second db with 2nd handle

you can make with the same handle as well

and dont use the MAKE connection thing inside a loop
unless it will make multiple connections
if you have no option, use mysql_pconenct
but if you put your code, i can tell you better
pein87's Avatar
Ambitious contributor
if your trying to query one database using fields from another you could but you'd need to know the fields before hand. Return the first database result as an associative array and us that in your second query. If you return both as the same array it should add the data together.
PHP Code:
= @mysql_connect('localhost','pein87','password');
$C2 = @mysql_connect('localhost:81','pein87','password');

$DB1 = @mysql_select_db('boo',$C1);
$DB2 =@mysql_select_db('boo'$C2);

$Q1 = @mysql_query("SELECT * FROM ghosts");

$ghostData = @mysql_fetch_assoc($Q1);

$Q2 = @mysql_query("SELECT * FROM ghostLocation WHERE '"$ghostData[HauntingType] ."' = 'demonic'");

$ghostData[] = @mysql_fetch_assoc($Q2);


This should work but of course you'll need to tweak your SQl statements though. What it will do is add more indexes to the $ghostData array. Knowing the fields of each table being called is essential for this to work though. I don't use array_merge() because of the overhead of calling a function when using $array_name[] = $Blah works better and faster. I hope this works out for you and as a rule of thumbs you'll need both connections because the mysql_select_db() will use the current active connection if you don't tell it which one to use.
etiergjt's Avatar
Light Poster
yes,it's not hard,I figured it out when I try to integrate wiki with phpbb,there is a ready-made wiki plugin do that to verify phpbb users