Home > Article > Backend Development > How to Dynamically Populate HTML Dropdown Lists with MySQL Data?
Integrating MySQL Data into HTML Dropdown Lists
This inquiry centers around the task of populating an HTML dropdown list with data retrieved from a MySQL database. Specifically, the desired outcome is to dynamically update the list with newly added agents in the company.
Solution:
To achieve this, one can employ the following approach:
Loop through the database query results, extracting the relevant information for each corresponding dropdown option.
The provided code snippet illustrates how to implement this solution:
<code class="php">// Presuming $db is a PDO object $query = $db->query("YOUR QUERY HERE"); // Execute your query echo '<select name="DROP DOWN NAME">'; // Initialize the dropdown // Iterate over query results, generating options dynamically while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo '<option value="'.htmlspecialchars($row['something']).'">'.htmlspecialchars($row['something']).'</option>'; } echo '</select>'; // Conclude the dropdown</code>
By utilizing this method, the HTML dropdown list will be dynamically populated with data from the MySQL database, ensuring that any new agents added to the system will automatically appear as options in the list.
The above is the detailed content of How to Dynamically Populate HTML Dropdown Lists with MySQL Data?. For more information, please follow other related articles on the PHP Chinese website!