How can two tables be simultaneously queried in PHP to retrieve specific data?

To query two tables simultaneously in PHP to retrieve specific data, you can use a SQL JOIN statement. By specifying the relationship between the tables in the JOIN condition, you can retrieve data from both tables based on specific criteria. This allows you to combine data from multiple tables into a single result set.

<?php
// Connect to 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 retrieve specific data from two tables
$sql = "SELECT table1.column1, table2.column2
        FROM table1
        JOIN table2 ON table1.id = table2.id
        WHERE table1.column1 = 'value'";

$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();
?>