Home > Database > Mysql Tutorial > How Can I Access Multiple MySQL Databases from a Single PHP Webpage?

How Can I Access Multiple MySQL Databases from a Single PHP Webpage?

DDD
Release: 2024-12-15 17:30:16
Original
731 people have browsed it

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

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

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

Alternative Options

If the user has access to both databases on the same host, consider these alternatives:

  • Single Connection with mysql_select_db(): Keep one connection open and switch databases using mysql_select_db(). However, this approach can lead to inconsistencies.
  • Database Specification in Queries: Specify the database name in your queries (e.g., SELECT * FROM database2.tablename). This option can be cumbersome, especially for complex queries.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template