Connecting multiple MySQL databases on a single web page is a common requirement in complex applications, especially when dealing with data aggregation or retrieving information from diverse data sources. While implementation details may vary slightly depending on the programming language and framework used, the fundamental workflow remains consistent. The following provides a PHP-based example:
-
Ensure proper environment configuration: First, verify that PHP and MySQL are installed on the server, and confirm your PHP environment supports MySQL database connections.
-
Establish database connections: In PHP, utilize the
mysqliorPDOextensions to create and manage database connections. For each database, instantiate a separate connection object. For example:
php// Create connection for database 1 $conn1 = new mysqli('host1', 'user1', 'password1', 'database1'); if ($conn1->connect_error) { die('Connection failed: ' . $conn1->connect_error); } // Create connection for database 2 $conn2 = new mysqli('host2', 'user2', 'password2', 'database2'); if ($conn2->connect_error) { die('Connection failed: ' . $conn2->connect_error); }
- Execute SQL queries: After establishing connections, run SQL queries for each database using the corresponding connection instance. For instance:
php// Retrieve data from database 1 $result1 = $conn1->query('SELECT * FROM table1'); while ($row = $result1->fetch_assoc()) { echo 'Data from database 1: ' . $row['column_name'] . '<br>'; } // Retrieve data from database 2 $result2 = $conn2->query('SELECT * FROM table2'); while ($row = $result2->fetch_assoc()) { echo 'Data from database 2: ' . $row['column_name'] . '<br>'; }
- Close database connections: Always close each connection after operations to free system resources.
php$conn1->close(); $conn2->close();
- Implement error handling and security: In production environments, handle potential errors and ensure SQL query security—such as using prepared statements to prevent SQL injection attacks.
This example serves as a basic template; depending on specific requirements, you may need to modify or extend the logic to enhance application adaptability and system robustness.