How do you connect to multiple MySQL databases on a single webpage?
Warning : mysql_xx
functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx
functions or see the answer below from @Troelskn
You can make multiple calls to mysql_connect()
, but if the parameters are the same you need to pass true for the '$new_link
' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2
) e.g.:
mysql_query('select * from tablename');
Other options
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
- Keep one connection open and call
mysql_select_db()
to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database. - Specify the database name when you reference tables within your queries (e.g.
SELECT * FROM database2.tablename
). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
How do you connect to multiple databases on a single webpage?
You can use multiple variables to point at different database connections. Just call the connect and assign the handle to another variable.
Related Topics
Sort Array of Objects by One Property
Passing Base64 Encoded Strings in Url
Compiling an Ast Back to Source Code
Convert Seconds to Hour:Minute:Second
Detecting Request Type in PHP (Get, Post, Put or Delete)
How to Strip All Spaces Out of a String in PHP
Detect Browser Language in PHP
MySQL Integer Field Is Returned as String in PHP
How to Create Websockets Server in PHP
Create Subdomains on the Fly With .Htaccess (PHP)
How to Get Multiple Selected Values of Select Box in PHP
What Are the PHP Operators "" and ":" Called and What Do They Do
How to Convert Date to Timestamp in PHP
Laravel Requires the Mcrypt PHP Extension