How to Populate an HTML Dropdown List with Data from a MySQL Database?

Susan Sarandon
Release: 2024-11-08 22:59:02
Original
351 people have browsed it

How to Populate an HTML Dropdown List with Data from a MySQL Database?

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:

  1. Execute an SQL query to fetch the needed data from the database. The query should return data in a suitable format for populating the dropdown list.
  2. Loop through the rows returned by the query. For each row, create an HTML option element with the relevant data from the row. The value attribute of the option element should hold the unique identifier for the record, while the visible text inside the option should represent the display value.
  3. Append the generated option elements to the HTML dropdown list.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template