What is the best way to display elements from a MySQL table in a dropdown list using PHP?
To display elements from a MySQL table in a dropdown list using PHP, you can first fetch the data from the table using a MySQL query. Then, loop through the results and create HTML <option> tags for each element to populate the dropdown list.
<?php
// Connect to MySQL 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);
}
// Fetch data from MySQL table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Create dropdown list
echo '<select>';
while($row = $result->fetch_assoc()) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';
// Close MySQL connection
$conn->close();
?>