Home >Backend Development >PHP Tutorial >How to Populate HTML Dropdown Lists with MySQL Data?

How to Populate HTML Dropdown Lists with MySQL Data?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 07:28:02273browse

How to Populate HTML Dropdown Lists with MySQL Data?

Populating 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.

Fetching Database Data

To achieve this, follow these steps:

  1. Establish a Database Connection: Establish a connection to your MySQL database using the appropriate PHP library, such as PDO.
  2. Execute a Query: Run a query to retrieve the agent names from your database.
  3. Loop Through Results: Iterate over each row returned by the query and extract the agent name.

Generating Dropdown List

Once you have the agent names, you can generate the dropdown list using HTML and PHP:

  1. Open the Dropdown: Begin the dropdown list element using tag.

Sample Code

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!

Statement:
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