Skip to content
PHP Logo

What is the best way to dynamically populate the options of an HTML select element using PHP and a database?

To dynamically populate the options of an HTML select element using PHP and a database, you can retrieve the data from the database using PHP and then loop through the results to generate the options for the select element. You can use a SQL query to fetch the data from the database and then iterate over the results to create the select options.

php
<?php
// Connect to the 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 the database
$sql = "SELECT id, name FROM options_table";
$result = $conn->query($sql);

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

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