What are some best practices for joining tables and displaying output in PHP?

When joining tables in PHP to display output, it is important to use proper SQL syntax to ensure accurate results. One common way to join tables is using the JOIN clause in SQL queries. Additionally, it is recommended to alias tables for better readability and to specify the columns to select in the query to avoid unnecessary data retrieval.

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

// SQL query to join tables and display output
$sql = "SELECT t1.column1, t2.column2
        FROM table1 AS t1
        JOIN table2 AS t2 ON t1.id = t2.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();
?>