I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
I know how to connect to a single database using:
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.
You don't actually need
select_db
. You can send a query to two databases at the same time. First, give a grant toDB1
to select fromDB2
byGRANT select ON DB2.* TO DB1@localhost;
. Then,FLUSH PRIVILEGES;
. Finally, you are able to do 'multiple-database query' likeSELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2
etc. (Don't forget that you need 'root' access to use grant command)if you are using mysqli and have two db_connection file. like first one is
second one is
SO just change the name of parameter pass in mysqli like DB1 and DB2. if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function
You might be able to use MySQLi syntax, which would allow you to handle it better.
Define the database connections, then whenever you want to query one of the database, specify the right connection.
E.g.:
Then to query them on the same page, use something like:
Changing to MySQLi in this way will help you.
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
(Of course replace databasename, username and password above)
You can then query the database like this:
Or, if you have variables:
If you need multiple connections open at once, you can simply create multiple instances of PDO:
This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.