What are the best practices for using JOINs in SQL queries within PHP to combine data from multiple tables?

When using JOINs in SQL queries within PHP to combine data from multiple tables, it is important to specify the columns you want to select and the type of JOIN you want to use (e.g., INNER JOIN, LEFT JOIN, RIGHT JOIN). Additionally, you should use table aliases to make the query more readable and avoid naming conflicts. Lastly, always sanitize user inputs to prevent SQL injection attacks.

<?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 JOINs
$sql = "SELECT t1.column1, t2.column2
        FROM table1 t1
        INNER JOIN table2 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();
?>