Populating HTML Dropdown Lists from MySQL Databases
Enriching your website's interactivity often requires retrieving data from databases for display purposes. Consider an HTML form containing a dropdown list that should display a roster of agents working in a company. To dynamically update this list as new agents are added, we can tap into the power of MySQL databases.
The key to this process lies in looping through the results of a database query and utilizing the retrieved information to populate the dropdown list's options. Here's an example:
<code class="php">$query = $db->query("SELECT * FROM agents"); // Execute database query echo '<select name="agent" id="agent">'; // Initialize the dropdown element while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo '<option value="' . htmlspecialchars($row['agent_id']) . '">' . htmlspecialchars($row['agent_name']) . '</option>'; } echo '</select>'; // Close the dropdown element</code>
This script first queries the database for all agents and then iterates over the results, creating an option for each agent in the dropdown list. The option's value attribute represents the agent's ID, while the displayed text contains the agent's name.
By leveraging database queries, your dropdown list remains up-to-date with real-time data, ensuring that new agents automatically appear as options whenever they are added to the database.
The above is the detailed content of How to Populate HTML Dropdown Lists from MySQL Databases?. For more information, please follow other related articles on the PHP Chinese website!