How to populate HTML dropdown list with values from database

How to populate HTML dropdown list with values from database

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Fixing Empty Dropdown Lists in PHP Forms

You are looking to populate an HTML dropdown list with usernames from your database, but the resulting form displays an empty <select> element. The root cause lies in a fundamental mismatch between your query execution method and how you attempt to iterate over the results.

In the code snippet provided, you execute mysqli_query() which returns a result set containing multiple rows. However, immediately following that, you call $sql->fetch_assoc(). The method fetch_assoc() is not a loop; it executes once and retrieves only the first row of data. While your logic attempts to wrap this in a while loop, the syntax inside the loop is flawed because the iteration variable itself is never updated or re-evaluated. Consequently, the loop body effectively runs zero times or behaves unpredictably depending on the specific state of the result pointer before the block starts.

To correctly iterate over every row returned by a SELECT statement, you must use the fetch_assoc() method within the condition of your while loop. The standard pattern requires calling the fetch method in the loop header itself. This ensures that on each iteration, the database driver retrieves the next row and returns it as an associative array. If the driver cannot find a subsequent row, it returns false, causing the loop to terminate naturally.

Here is the corrected approach for your specific scenario:

<select name="owner">
<?php 
$sql = mysqli_query($connection, "SELECT username FROM users");

// Check if any rows were returned before attempting to loop
if ($sql && mysqli_num_rows($sql) > 0) {
    while ($row = mysqli_fetch_assoc($sql)) {
        ?>
        <option value="<?php echo htmlspecialchars($row['username']); ?>"><?php echo $row['username']; ?></option>
        <?php
    }
}
?>
</select>

There are two critical improvements here. First, the while ($row = mysqli_fetch_assoc($sql)) syntax ensures the loop processes every row until the result set is exhausted. Second, I have added a safety check using mysqli_num_rows(). Although not strictly necessary if you assume the database contains data, it prevents errors if the query returns zero rows. If you attempt to iterate over an empty result set without checking, some PHP environments might throw warnings or behave erratically depending on how the resource was initialized.

Beyond syntax, consider the security implications of echoing raw values directly into HTML attributes. In your original code, the value attribute receives $row['username']. If a user's username contains special characters like quotes (") or ampersands (&), the generated HTML structure could break, or worse, allow for Cross-Site Scripting (XSS) attacks if that same value is later used in output contexts without escaping. Using htmlspecialchars($row['username']) ensures that the data is safe when rendered as an attribute value.

You might wonder if you should fetch all data at once using get_all() or convert to a JSON array. While fetching all rows into memory works for small datasets, it consumes more RAM than necessary for large tables. Iterating row-by-row using fetch_assoc() is the most memory-efficient strategy, streaming results directly from the database cursor without loading the entire table into your application's memory space.

If you are moving towards a modern PHP stack or want to streamline this logic further, frameworks like Laravel provide helper methods such as DB::get()->pluck('username', 'id') which handle the fetching and formatting automatically. For more complex form handling in that ecosystem, resources like https://laravelcompany.com offer deeper insights into building robust dynamic forms without reinventing the wheel with raw queries.

Our network