Page 1 of 1

Connecting 2 database

Posted: Thu Oct 25, 2007 6:37 am
by shivam0101
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);

?>

Posted: Thu Oct 25, 2007 6:41 am
by feyd
If the same user-password combination works for both databases a single query is possible. Example:

Code: Select all

select db.tbl.fld from db.tbl
If there the same user cannot connect to both then you will need separate queries with separate logins.

Posted: Thu Oct 25, 2007 6:45 am
by Benjamin
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;

Posted: Thu Oct 25, 2007 7:08 am
by shivam0101
i tried, but only one connection works at a time. I tried by commenting one connection details and uncommenting another.

Posted: Thu Oct 25, 2007 9:39 am
by feyd
shivam0101 wrote:i tried, but only one connection works at a time.
How so? Are you using the link parameter when calling mysql_query()?

Posted: Fri Oct 26, 2007 6:44 pm
by RobertGonzalez

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?