How can PHP be used to efficiently handle complex data relationships between tables in a MySQL database?

To efficiently handle complex data relationships between tables in a MySQL database using PHP, you can utilize SQL JOIN queries to fetch related data from multiple tables in a single query. This helps reduce the number of database queries and improves performance by minimizing the amount of data transferred between the database and the PHP application.

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

// Query to fetch data from multiple tables using JOIN
$query = "SELECT users.username, orders.order_id, orders.total_price 
          FROM users 
          JOIN orders ON users.user_id = orders.user_id";

$result = mysqli_query($connection, $query);

// Loop through the results and process the data
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Username: " . $row['username'] . " | Order ID: " . $row['order_id'] . " | Total Price: " . $row['total_price'] . "<br>";
    }
} else {
    echo "No results found.";
}

// Close the database connection
mysqli_close($connection);
?>