What are best practices for managing multiple MySQL database connections in PHP?

When managing multiple MySQL database connections in PHP, it is best practice to use a connection pooling technique to efficiently manage and reuse connections. This helps reduce the overhead of opening and closing connections for each database operation, leading to better performance and scalability.

<?php

// Create an array to store multiple database connection objects
$connections = [];

function getDbConnection($host, $username, $password, $database) {
    global $connections;

    // Check if a connection already exists for the given host
    if(isset($connections[$host])) {
        return $connections[$host];
    }

    // Create a new database connection object
    $connection = new mysqli($host, $username, $password, $database);

    // Check for connection errors
    if($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    // Store the connection object in the array
    $connections[$host] = $connection;

    return $connection;
}

// Example usage
$connection1 = getDbConnection('localhost', 'username1', 'password1', 'database1');
$connection2 = getDbConnection('localhost', 'username2', 'password2', 'database2');

// Use the connections for database operations
// Remember to close the connections when done
$connection1->close();
$connection2->close();

?>