What is the recommended approach for fetching data from multiple tables in PHP?

When fetching data from multiple tables in PHP, it is recommended to use SQL JOIN queries to combine data from different tables based on a related column. This allows you to retrieve the required information in a single query rather than making multiple queries and then combining the results in PHP code.

<?php
// Connect to the database
$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);
}

// Fetch data from multiple tables using SQL JOIN
$sql = "SELECT users.name, orders.product FROM users
        JOIN orders ON users.id = orders.user_id";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "User: " . $row["name"]. " - Product: " . $row["product"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>