How can JOIN commands be used to connect data from two separate tables in PHP?

When you have data stored in two separate tables in a database and you need to connect them based on a common column, you can use SQL JOIN commands in PHP to retrieve the combined data. By using JOIN commands such as INNER JOIN, LEFT JOIN, or RIGHT JOIN, you can merge the data from the two tables based on a specified condition. This allows you to retrieve related data from different tables in a single query.

<?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 to join data from two tables based on a common column
$sql = "SELECT table1.column1, table1.column2, table2.column3
        FROM table1
        INNER JOIN table2 ON table1.common_column = table2.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"]. " - Column3: " . $row["column3"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>