Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.
Moderator: General Moderators
shivam0101
Forum Contributor
Posts: 197 Joined: Sat Jun 09, 2007 12:09 am
Post
by shivam0101 » Thu Oct 25, 2007 6:37 am
How to connect to 2 database from different server. I have to display client_details on the left side and blog_details on the right side on the same page. client_details and blog_details tables are in different databases. say db1 and db2.
Config file details:
Code: Select all
<?php
$host = 'host1';
$username = 'user1';
$password ='password1';
$database='db1';
$link=mysql_connect($host, $username, $password);
mysql_select_db($database, $link);
$host2 = 'host2';
$username2= 'user2';
$password2 ='password2';
$database='db2';
$blog_link=mysql_connect($host2, $username2, $password2);
$blog_database='db2';
mysql_select_db($blog_database, $blog_link);
?>
Last edited by
shivam0101 on Thu Oct 25, 2007 6:55 am, edited 1 time in total.
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Thu Oct 25, 2007 6:41 am
If the same user-password combination works for both databases a single query is possible. Example:
If there the same user cannot connect to both then you will need separate queries with separate logins.
Benjamin
Site Administrator
Posts: 6935 Joined: Sun May 19, 2002 10:24 pm
Post
by Benjamin » Thu Oct 25, 2007 6:45 am
You don't. You connect to one, and specify the database in the query.
Code: Select all
select
a.field_one,
b.field_two
from
database_a.table_a a,
database_b.table_b b
where
a.foo = bar
and a.id = b.id
order by
b.field_two
Code: Select all
select * from database_one.foo;
select * from database_two.bar;
shivam0101
Forum Contributor
Posts: 197 Joined: Sat Jun 09, 2007 12:09 am
Post
by shivam0101 » Thu Oct 25, 2007 7:08 am
i tried, but only one connection works at a time. I tried by commenting one connection details and uncommenting another.
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Thu Oct 25, 2007 9:39 am
shivam0101 wrote: i tried, but only one connection works at a time.
How so? Are you using the
link parameter when calling
mysql_query() ?
RobertGonzalez
Site Administrator
Posts: 14293 Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA
Post
by RobertGonzalez » Fri Oct 26, 2007 6:44 pm
Code: Select all
<?php
// Client database connection
$host = 'host1';
$username = 'user1';
$password ='password1';
$database='db1';
$db_client = mysql_connect($host, $username, $password);
mysql_select_db($database, $db_client);
var_dump($db_client);
// Now the blog database connection
$host2 = 'host2';
$username2= 'user2';
$password2 ='password2';
$database2='db2';
$db_blog=mysql_connect($host2, $username2, $password2);
mysql_select_db($database2, $db_blog);
var_dump($db_blog);
?>
What does this output?