What potential issues can arise when trying to display related data from multiple tables in PHP?

One potential issue that can arise when trying to display related data from multiple tables in PHP is the need to perform JOIN operations in the database query to retrieve the related data. This can be complex and error-prone if not done correctly. One way to solve this is to use SQL JOIN statements in the query to fetch data from multiple tables based on a common key.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Select data from multiple tables using JOIN
$sql = "SELECT t1.column1, t2.column2 
        FROM table1 t1 
        JOIN table2 t2 ON t1.common_key = t2.common_key";

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

if ($result->num_rows > 0) {
    // Output data from query
    while($row = $result->fetch_assoc()) {
        echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>