How can JOINs be utilized in PHP to combine data from multiple tables for more complex queries?

When working with databases in PHP, JOINs can be used to combine data from multiple tables in a single query. This is particularly useful for complex queries where data from different tables needs to be retrieved and correlated. By using JOINs, you can avoid making multiple queries and instead fetch all the required data in one go.

<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Query to select data from two tables using INNER JOIN
$query = "SELECT users.username, orders.product_name FROM users INNER JOIN orders ON users.id = orders.user_id";

// Execute the query
$result = $connection->query($query);

// Loop through the results and display them
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row['username'] . " - Product: " . $row['product_name'] . "<br>";
}

// Close the connection
$connection->close();
?>