How can JOINs be utilized to optimize database queries for fetching user profile picture paths in PHP?

When fetching user profile picture paths in PHP, JOINs can be utilized to optimize the database queries by combining related tables efficiently. By using JOINs, we can retrieve the necessary data from multiple tables in a single query, reducing the number of database calls and improving performance.

// Assuming we have a users table with user_id and profile_pictures table with user_id and picture_path

// Establish database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Query to fetch user profile picture paths using JOIN
$sql = "SELECT users.user_id, profile_pictures.picture_path 
        FROM users 
        LEFT JOIN profile_pictures ON users.user_id = profile_pictures.user_id";

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

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "User ID: " . $row["user_id"]. " - Profile Picture Path: " . $row["picture_path"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close database connection
$conn->close();