Subha
Subha

Reputation: 761

PHP how to connect more then one db

how to connect more then one DB in php... but the DB servers are same . but the DB is different. same single page i need to fetch the result from all the 3 db to display. Thank you

Upvotes: 2

Views: 218

Answers (4)

Amy B
Amy B

Reputation: 17977

Method 1:

Don't select databases; put the database name before the table:

mysql_connect('localhost','db_user','pssword');
mysql_query('SELECT * FROM database_1.table_name');

Method 2:

$handle_db1 = mysql_connect("localhost","myuser","apasswd");
$handle_db2 = mysql_connect("127.0.0.1","myuser","apasswd");
$handle_db3 = mysql_connect("localhost:3306","myuser","apasswd");
$handle_db4 = mysql_connect("localhost","otheruser","apasswd");

mysql_select_db("db1",$handle_db1);
mysql_select_db("db2",$handle_db2);
mysql_select_db("db3",$handle_db3);
mysql_select_db("db4",$handle_db4);

//do a query from db1:
$query = "select * from test"; $which = $handle_db1;
mysql_query($query,$which);

//do a query from db2 :
$query = "select * from test"; $which = $handle_db2;
mysql_query($query,$which); 

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157828

http://php.net/mysql_connect, note the parameters

also, if all these DBs share same server, you can just specify particular db using . syntax:

SELECT * FROM db1.table ...
SELECT * FROM db2.table ...
SELECT * FROM db3.table ...

Upvotes: 0

staticsan
staticsan

Reputation: 30555

Easy: make multiple connections. Each connection returns a resource handle which you assign to a variable. So you just put each connection into it's own variable.

Upvotes: 1

Young
Young

Reputation: 8356

Just building more database handles,that's just fine.

Upvotes: 0

Related Questions