How can JOIN be utilized to improve performance when querying data from multiple databases in PHP?
When querying data from multiple databases in PHP, JOIN can be utilized to improve performance by combining related data from different tables. By using JOIN, you can fetch data from multiple tables in a single query instead of making separate queries for each table, reducing the number of database calls and improving efficiency.
<?php
// Connect to the first database
$database1 = new PDO('mysql:host=localhost;dbname=database1', 'username', 'password');
// Connect to the second database
$database2 = new PDO('mysql:host=localhost;dbname=database2', 'username', 'password');
// Perform a JOIN query to fetch data from both databases
$query = "SELECT * FROM database1.table1
JOIN database2.table2
ON database1.table1.id = database2.table2.id";
$statement = $database1->query($query);
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
// Process the results
foreach ($results as $row) {
// Do something with the data
}
?>