How can the SQL syntax be optimized to ensure accurate results when fetching data from multiple tables in PHP?

When fetching data from multiple tables in PHP using SQL, it's important to optimize the SQL syntax to ensure accurate results. One way to do this is by using JOIN statements to combine the tables based on a common key. This helps to minimize the number of queries executed and improve the efficiency of the data retrieval process.

<?php
// Establish a connection to the 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);
}

// SQL query with JOIN to fetch data from multiple tables
$sql = "SELECT * FROM table1 
        JOIN table2 ON table1.common_key = table2.common_key 
        WHERE condition";

$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();
?>