Home >Backend Development >PHP Tutorial >How to Connect to Multiple MySQL Databases from a Single PHP Webpage?

How to Connect to Multiple MySQL Databases from a Single PHP Webpage?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 20:44:14507browse

How to Connect to Multiple MySQL Databases from a Single PHP Webpage?

Connecting to Multiple MySQL Databases on a Single Webpage

Question:

How can we establish connections to multiple MySQL databases within a single PHP webpage? Currently, we are aware of connecting to a single database using mysql_connect(). However, we want to extend this functionality to multiple databases.

Answer:

Using multiple mysql_connect() commands is possible for connecting to different databases, but it requires specifying true for the fourth parameter ('new_link') to prevent reusing the same connection. For instance:

$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);

To select a specific database, pass the corresponding link identifier:

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);

Then, use the link identifier when executing queries:

mysql_query('SELECT * FROM tablename', $dbh1); // database1
mysql_query('SELECT * FROM tablename', $dbh2); // database2

Warning: It's important to note that mysql_connect() is deprecated in PHP 7.0 and removed in PHP 7.2. It is recommended to use the newer PDO functions for database connectivity.

The above is the detailed content of How to Connect to Multiple MySQL Databases from a Single PHP Webpage?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn