mysqllearner
mysqllearner

Reputation: 13913

How to connect 2 databases in php and mysql?

I have 2 databases. Users database and purchases database. Each database has different user and password.

If i want to execute a query to call both databases. How do I connect the databases?

$db = mysql_select_db(??????);

Upvotes: 0

Views: 353

Answers (3)

Pesse
Pesse

Reputation: 411

$db1 = mysql_connect($host1, $user1, $pass1);
mysql_select_db($db1, 'database1');

$db2 = mysql_connect($host2, $user2, $pass1);
mysql_select_db($db2, 'database2');

$query = "SELECT * FROM test";

mysql_query($db1, $query);
mysql_query($db2, $query);

EDIT: Ok, now I understand the problem (reading the comments to the other answers): If you don't have the permission, you will not be able to do a statement which connects 2 databases. If you have a user, which has permission to select from both databases, it should be possible by

SELECT * FROM db1.table, db2.table

Upvotes: 1

Fredrik
Fredrik

Reputation: 5849

call mysql_connect() twice and store the result in a variable. that variable can then be sent to just about every mysql_* call in php to tell you which one you are referring two. Look at the second argument of mysql_select_db() and you will understand.

Edit: This way, you will of course not be able to use them both in the same query but unless your database users have granted access to both, I think it is your only option.

Upvotes: 0

RageZ
RageZ

Reputation: 27323

You don't have to care which db you select since you are giving to MySQL the database name in the queries.

i.e

SELECT * FROM db.table, db2.table

So whatever database you have selected it won't change a thing.

Upvotes: 1

Related Questions