Organizational Research By

Surprising Reserch Topic

How to connect to multiple databases in a single PHP page?


If I want to connect to one db do some query, and then later do another query from another DB. How do I do it? Do I just

 mysql_pconnect("host:3306", "user", "password") or die(mysql_error());
 mysql_select_db("Test") or die(mysql_error());

//do some query

 mysql_pconnect("host2:3306", "user", "password") or die(mysql_error());
 mysql_select_db("Test") or die(mysql_error());

//do another query

Is that how you do it? A couple of questions. Notice I used pconnect, does that affect calling it twice on the same page? Also, do I have to close the connection for the first one before calling the second one?


asked May 8, 2015 in PHP by rajesh
0 votes
18 views



Related Hot Questions

1 Answer

0 votes

You need to store database connection link in separate variable. For example

 $connection_1 = mysql_connect("host:3306", "user", "password") or die(mysql_error());
 mysql_select_db("Test", $connection_1) or die(mysql_error());

 $connection_2 = mysql_pconnect("host2:3306", "user", "password") or die(mysql_error());
 mysql_select_db("Test", $connection_2) or die(mysql_error());

 mysql_query("your query", $connection_1); // run query for first connection
 mysql_query("your query", $connection_2); // run query for second connection
answered May 8, 2015 by rajesh

...