PHP: Populating a drop down list from MySQL.

This is an extremely simply tutorial on how to populate a drop down list using values that you’ve selected from MySQL. In this guide, I will be using PHP to retrieve the data and populate a SELECT element.

In the following example, we retrieve a list of users from MySQL using PHP and the PDO object. We then loop through the result set so that we can populate our dropdown SELECT element:

A quick overview of the code above:

  1. We connect to MySQL using the PDO object.
  2. We select rows from our users table using a prepared statement.
  3. We then loop through the results and print out the option values for our SELECT tag. In this case, we display the name of the user in the dropdown.

The resulting SELECT tag will look something like this:

Note: When populating SELECT tags with database rows, it is a good idea to insert the primary key value into the value attribute of each <option> tag. This means that the option value will contain the unique primary key of the row in question. This was required in the example above, simply because two users may have the exact same name.