How can a JOIN statement be utilized to combine data from two tables in PHP for efficient data retrieval?

When combining data from two tables in PHP for efficient data retrieval, a JOIN statement can be utilized to merge the tables based on a common column. This allows for the retrieval of related data in a single query, reducing the need for multiple queries and improving performance.

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

// Query to select data from two tables using a JOIN statement
$sql = "SELECT table1.column1, table2.column2 
        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"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>