How can PHP queries be optimized to retrieve data from multiple tables using JOIN statements?

To optimize PHP queries to retrieve data from multiple tables using JOIN statements, you can specify the columns you need in the SELECT statement, use appropriate JOIN conditions, and avoid selecting unnecessary data. Additionally, you can use indexes on the columns being joined to improve query performance.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query with JOIN statement
$sql = "SELECT users.username, orders.order_id FROM users JOIN orders ON users.user_id = orders.user_id";

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

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

$conn->close();
?>