How can PHP be used to dynamically generate HTML code, such as populating a dropdown list from a database?

To dynamically generate HTML code, such as populating a dropdown list from a database, you can use PHP to fetch data from the database and then loop through the results to create the HTML code for the dropdown list. This can be achieved by using PHP's database connection functions to retrieve the data and then using a loop to generate the HTML code for each option in the dropdown list.

<?php
// Assuming you have already established a database connection

// Query to fetch data from the database
$query = "SELECT id, name FROM options_table";
$result = mysqli_query($connection, $query);

// Generate HTML code for the dropdown list
echo '<select name="dropdown">';
while ($row = mysqli_fetch_assoc($result)) {
    echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';

// Close the database connection
mysqli_close($connection);
?>