Home >Database >Mysql Tutorial >How Can I Access Multiple MySQL Databases from a Single PHP Webpage?
Accessing Multiple MySQL Databases on a Single Webpage with PHP
Connecting to multiple MySQL databases from a single PHP webpage is possible using the mysql_connect function. However, certain considerations should be made to ensure correct database usage.
Connecting Multiple Databases
To connect to multiple databases, make multiple calls to mysql_connect with the same parameters. Pass true as the fourth (new link) parameter to establish a new connection for each database. For example:
$dbh1 = mysql_connect($hostname, $username, $password); $dbh2 = mysql_connect($hostname, $username, $password, true);
Selecting Databases
Once connected, use mysql_select_db to specify which database to query from. Pass the link identifier as the second parameter. For example:
mysql_select_db('database1', $dbh1); mysql_select_db('database2', $dbh2);
Querying Databases
To query a specific database, pass the corresponding link identifier as the first parameter to mysql_query. If no link identifier is specified, the last connection created will be used. For example:
// Query database 1 mysql_query('select * from tablename', $dbh1); // Query database 2 mysql_query('select * from tablename', $dbh2);
Alternative Options
If the user has access to both databases on the same host, consider these alternatives:
The above is the detailed content of How Can I Access Multiple MySQL Databases from a Single PHP Webpage?. For more information, please follow other related articles on the PHP Chinese website!