How can PDO be used to handle database selection dynamically in PHP scripts?

When needing to dynamically select a database in PHP scripts using PDO, you can achieve this by creating a PDO connection with the database information and then switching the database by executing a SQL query to change the database context. This can be useful when working with multiple databases or when the database needs to be selected based on certain conditions.

<?php
// Database connection information
$host = 'localhost';
$username = 'username';
$password = 'password';

// Create a PDO connection
$pdo = new PDO("mysql:host=$host;dbname=database1", $username, $password);

// Switch to a different database dynamically
$databaseName = 'database2';
$pdo->exec("USE $databaseName");

// Now you can perform queries on the selected database
$stmt = $pdo->query("SELECT * FROM table_name");
while ($row = $stmt->fetch()) {
    // Process the data
}
?>