How can data from two tables be retrieved using an ID in PHP?

To retrieve data from two tables using an ID in PHP, you can use a SQL query with a JOIN statement to combine the data from both tables based on the common ID. This allows you to fetch related data from multiple tables in a single query. Make sure to properly sanitize the input ID to prevent SQL injection attacks.

<?php
// Assuming $id contains the ID to retrieve data
$id = $_GET['id'];

// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to retrieve data from two tables using the ID
$sql = "SELECT * FROM table1
        JOIN table2 ON table1.id = table2.id
        WHERE table1.id = $id";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Output data from both tables
        echo "Table 1 data: " . $row['column1'] . "<br>";
        echo "Table 2 data: " . $row['column2'] . "<br>";
    }
} else {
    echo "No data found";
}

$conn->close();
?>