How to Populate an HTML Dropdown List with Data from a MySQL Database
To dynamically populate an HTML dropdown list with data retrieved from a MySQL database, follow these steps:
An example code using PDO to achieve this:
<code class="php">// Assume $db is a PDO object $query = $db->query("SELECT id, name FROM agents"); // Run your query echo '<select name="agents">'; // 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="'.$row['id'].'">'.$row['name'].'</option>'; } echo '</select>';// Close your drop down box</code>
By following these steps, you can populate your HTML dropdown list with data retrieved from your MySQL database, ensuring that newly added agents are automatically available as options in the dropdown.
The above is the detailed content of How to Populate an HTML Dropdown List with Data from a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!