What are the potential pitfalls of querying multiple MySQL tables in a loop in PHP?

Querying multiple MySQL tables in a loop in PHP can lead to a high number of database queries being executed, which can impact performance and slow down the application. To solve this issue, you can use SQL JOIN statements to combine data from multiple tables into a single query, reducing the number of queries sent to the database.

// Example of using SQL JOIN to query multiple tables in PHP
$query = "SELECT users.username, orders.order_id
          FROM users
          JOIN orders ON users.user_id = orders.user_id";

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

if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        echo "Username: " . $row['username'] . " - Order ID: " . $row['order_id'] . "<br>";
    }
}