How can the code be optimized by combining multiple database queries into one in PHP?

Combining multiple database queries into one can optimize the code by reducing the number of round trips to the database, thus improving performance. This can be achieved by using JOINs in SQL queries to retrieve data from multiple tables in a single query rather than making separate queries for each table.

// Example of combining multiple database queries into one using JOINs 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>";
    }
} else {
    echo "No results found.";
}