What are some potential pitfalls when trying to output data from multiple MySQL tables in PHP?

One potential pitfall when trying to output data from multiple MySQL tables in PHP is not properly handling the relationships between the tables. To solve this, you can use SQL JOIN statements to combine data from multiple tables based on a common column.

<?php
// Connect to MySQL 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);
}

// Query to select data from multiple tables using JOIN
$sql = "SELECT orders.order_id, customers.customer_name
        FROM orders
        JOIN customers ON orders.customer_id = customers.customer_id";

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

if ($result->num_rows > 0) {
    // Output data from multiple tables
    while($row = $result->fetch_assoc()) {
        echo "Order ID: " . $row["order_id"]. " - Customer Name: " . $row["customer_name"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>