How can PHP be used to output selected data from a database in a dropdown menu?

To output selected data from a database in a dropdown menu using PHP, you can first query the database to retrieve the desired data. Then, loop through the results to generate the options for the dropdown menu. Finally, echo out the HTML code for the dropdown menu with the dynamically generated options.

<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

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

// Generate options for the dropdown menu
$options = '';
while ($row = mysqli_fetch_assoc($result)) {
    $options .= '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}

// Echo out the HTML code for the dropdown menu
echo '<select name="dropdown">' . $options . '</select>';

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