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!