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
Release: 2024-12-20 20:44:14
Original
436 people have browsed it

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);
Copy after login

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

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Copy after login

Then, use the link identifier when executing queries:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template