Is it possible to achieve the desired output with a single query in PHP?

To achieve the desired output with a single query in PHP, you can use a SQL JOIN statement to combine data from multiple tables into a single result set. This allows you to retrieve related data in a single query rather than making multiple queries and then combining the results in your PHP code.

<?php
// Connect to database
$connection = new mysqli('localhost', 'username', 'password', 'database');

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

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

$result = $connection->query($query);

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

// Close connection
$connection->close();
?>