How can Joins be used in PHP to display the corresponding names instead of IDs in a Combobox?

When displaying data from a database in a Combobox, it is common to have IDs as values instead of the corresponding names. To display the names instead of IDs, we can use a SQL JOIN query to fetch the names from another table based on the IDs. By using the JOIN query, we can combine data from multiple tables and display the corresponding names in the Combobox.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Fetch data with JOIN query
$sql = "SELECT t1.id, t2.name FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id";
$result = $conn->query($sql);

// Display data in Combobox
echo "<select>";
while($row = $result->fetch_assoc()) {
    echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";

// Close database connection
$conn->close();
?>