Home > Article > Backend Development > How to Populate HTML Dropdown Lists with MySQL Data?
In web development, dynamic data often needs to be displayed in user-friendly interfaces. An example of this is fetching agent names from a MySQL database to fill a dropdown list on a web form.
To achieve this, follow these steps:
Once you have the agent names, you can generate the dropdown list using HTML and PHP:
The following code illustrates this process:
<code class="php">// Assuming $db is a PDO object $query = $db->query("SELECT agent_name FROM agents"); // Run your query echo '<select name="agent">'; // Open the dropdown // Loop through the query results, outputting the options one by one. while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo '<option value="' . htmlspecialchars($row['agent_name']) . '">' . htmlspecialchars($row['agent_name']) . '</option>'; } echo '</select>'; // Close the dropdown</code>
In this example, $db is a PDO object and agent_name is the column name in your database that contains the agent names. By following these steps, you can dynamically populate dropdown lists with data from a MySQL database, ensuring that new agents are automatically added to the list.
The above is the detailed content of How to Populate HTML Dropdown Lists with MySQL Data?. For more information, please follow other related articles on the PHP Chinese website!