What is the purpose of using a JOIN in PHP when retrieving data from multiple tables?
When retrieving data from multiple tables in a database, a JOIN in PHP is used to combine rows from two or more tables based on a related column between them. This allows us to fetch data that is spread across different tables and present it as a single result set. Using JOINs in PHP helps avoid making multiple queries and improves performance by fetching all the required data in one go.
<?php
// Establish a database connection
$connection = new mysqli("localhost", "username", "password", "database");
// Query to retrieve data from multiple tables using a JOIN
$query = "SELECT table1.column1, table2.column2
FROM table1
JOIN table2 ON table1.id = table2.table1_id";
$result = $connection->query($query);
// Fetch and display the data
while ($row = $result->fetch_assoc()) {
echo $row['column1'] . " - " . $row['column2'] . "<br>";
}
// Close the database connection
$connection->close();
?>