What are the potential pitfalls of connecting to and querying multiple databases in PHP sequentially?

Connecting to and querying multiple databases in PHP sequentially can lead to slower performance due to the overhead of establishing multiple connections. To solve this issue, you can use a database connection pooling technique where connections to multiple databases are maintained and reused, reducing the overhead of establishing new connections each time a query is executed.

// Create a function to establish a database connection
function connectToDatabase($host, $username, $password, $database) {
    $connection = new mysqli($host, $username, $password, $database);
    
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }
    
    return $connection;
}

// Example of connecting to multiple databases using connection pooling
$database1 = connectToDatabase('host1', 'username1', 'password1', 'database1');
$database2 = connectToDatabase('host2', 'username2', 'password2', 'database2');

// Use $database1 and $database2 for querying data from multiple databases