What are the common pitfalls when using MySQL queries in PHP for fetching and displaying data from multiple tables?

Common pitfalls when using MySQL queries in PHP for fetching and displaying data from multiple tables include not properly joining the tables, not sanitizing user input which can lead to SQL injection attacks, and not handling errors effectively. To solve these issues, always use proper SQL JOIN statements, use prepared statements or parameterized queries to prevent SQL injection, and implement error handling to catch any potential issues.

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

// Fetch data from multiple tables using JOIN
$sql = "SELECT * FROM table1
        JOIN table2 ON table1.id = table2.table1_id";

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

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>