How can different databases with the same structure be effectively queried in PHP?

When querying different databases with the same structure in PHP, you can use PDO (PHP Data Objects) to connect to the databases and execute queries. By dynamically specifying the database connection details, you can easily switch between databases without changing the query logic.

<?php

// Database connection details
$database1 = new PDO('mysql:host=localhost;dbname=database1', 'username', 'password');
$database2 = new PDO('mysql:host=localhost;dbname=database2', 'username', 'password');

// Specify the database to use
$selectedDatabase = $database1;

// Query example
$query = $selectedDatabase->prepare("SELECT * FROM table_name");
$query->execute();
$results = $query->fetchAll();

// Process results
foreach ($results as $row) {
    // Do something with the data
}

?>