How can JOIN statements be effectively utilized in PHP to combine data from different tables for comparison?
When using JOIN statements in PHP, you can combine data from different tables by specifying the columns to join on and the type of join (e.g., INNER JOIN, LEFT JOIN). This allows you to retrieve related data from multiple tables in a single query for comparison or analysis. By using JOIN statements effectively, you can streamline your database queries and avoid the need for multiple separate queries to fetch related data.
<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to select data from multiple tables using JOIN
$sql = "SELECT table1.column1, table2.column2
FROM table1
INNER JOIN table2 ON table1.id = table2.id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data from query
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>