What are the best practices for managing database connections in PHP when dealing with multiple databases?

When dealing with multiple databases in PHP, it is important to manage database connections efficiently to avoid performance issues and resource wastage. One common approach is to create separate connection objects for each database and reuse them where possible. Additionally, using connection pooling or a connection manager can help optimize the handling of database connections.

// Create separate connection objects for each database
$database1 = new PDO('mysql:host=localhost;dbname=database1', 'username', 'password');
$database2 = new PDO('mysql:host=localhost;dbname=database2', 'username', 'password');

// Reuse connections where possible
// Example query using $database1
$stmt = $database1->query('SELECT * FROM table1');
$results = $stmt->fetchAll();

// Example query using $database2
$stmt = $database2->query('SELECT * FROM table2');
$results = $stmt->fetchAll();

// Close connections when done
$database1 = null;
$database2 = null;