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
}
?>
Keywords
Related Questions
- What are some alternative approaches to handling linked HTML files in a PHP application, aside from storing all files in a database?
- How can multiple users accessing a file simultaneously affect the execution of a PHP script?
- What common beginner mistakes should be avoided when creating a PHP program that interacts with a database?