Populating HTML Dropdown Lists from a MySQL Database
Creating a drop-down list populated with data from a MySQL database enhances the user experience and simplifies form management. To achieve this, we can establish a connection to the database and retrieve the necessary data through a query.
Let's dive into the code:
// Assume $db is a PDO object $query = $db->query("YOUR QUERY HERE"); // Run your query echo '<select name="DROP DOWN NAME">'; // Open your drop down box // Loop through the query results, outputing the options one by one while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo '<option value="'.htmlspecialchars($row['something']).'">'.$row['something'].'</option>'; } echo '</select>';// Close your drop down box
Here's a breakdown of the code:
By incorporating this code into your form, you can dynamically populate the drop-down list with data from your MySQL database. This enables you to maintain a current and accurate list of options without manual updates.
The above is the detailed content of How to Populate HTML Dropdown Lists with Data from a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!