What are some best practices for querying and fetching data from multiple tables in PHP using SQL statements?

When querying and fetching data from multiple tables in PHP using SQL statements, it is best practice to use JOIN clauses to combine the tables based on a common column. This allows you to retrieve related data from different tables in a single query. Additionally, you should specify the columns you want to select to avoid unnecessary data retrieval and improve performance.

<?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);
}

// Query to fetch data from multiple tables using JOIN
$sql = "SELECT t1.column1, t2.column2
        FROM table1 t1
        JOIN table2 t2 ON t1.common_column = t2.common_column";

$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";
}

// Close database connection
$conn->close();

?>