How can you join tables in a MySQL query to retrieve related data in PHP?

When you have data stored in multiple tables in a MySQL database and you need to retrieve related data, you can use JOIN operations in your SQL query. By specifying how the tables are related using JOIN clauses, you can combine data from different tables into a single result set. In PHP, you can execute the SQL query using mysqli or PDO to retrieve the related data and process it as needed.

<?php
// Establish a connection to the MySQL 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);
}

// SQL query to retrieve related data using JOIN
$sql = "SELECT orders.order_id, customers.customer_name
        FROM orders
        JOIN customers ON orders.customer_id = customers.customer_id";

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

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Order ID: " . $row["order_id"]. " - Customer Name: " . $row["customer_name"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>