selected value get from db into dropdown select box option using php mysql error

selected value get from db into dropdown select box option using php mysql error

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

Stefan Bogdanescu

Founder & Senior Architect

Populating Dropdown Options from Database Values in PHP and MySQL

The code snippet provided attempts to retrieve user-specific data—username, category, and options—from a database and render it into an HTML form. While the intent is clear, the implementation relies on deprecated functions and contains critical logic errors that prevent the "selected" state from working correctly. Specifically, the mysql_* extension has been removed from PHP core since version 5.5.0 in favor of PDO or MySQLi. Furthermore, using single quotes within double-quoted strings for string interpolation often leads to confusion regarding variable scope, and the logic for populating the <option> tags is incomplete given the requirement that options depend on the category.

To fix the security vulnerabilities immediately, you must switch from mysql_query to a prepared statement. Using direct variable interpolation in SQL queries exposes your application to SQL injection attacks if the $user input contains malicious characters. A secure alternative using PDO looks like this:

$stmt = $pdo->prepare("SELECT category, username, options FROM mine WHERE username = :user");
$stmt->execute(['user' => $user]);
$row = $stmt->fetch();

if ($row) {
    $category = htmlspecialchars($row['category']);
    $username = htmlspecialchars($row['username']);
    
    // Output the read-only category field
    echo "<input type='text' name='category' value='" . htmlspecialchars($row['category']) . "' readonly>";
}

The second major issue in your original code is how the <select> element renders its options. You are hardcoding static values like "PHP" and "ASP". If the database field options contains a list of courses for that specific category, those static values will never match the data stored in $row['options'], resulting in no option being selected when the page loads.

To dynamically populate the dropdown so that one option is pre-selected based on the current row's data, you need to iterate over the available options and compare their values against a target value. First, determine what constitutes the "selected" state. If the $options column stores a comma-separated list like "PHP,ASP,MySQL", you must parse that string into an array to check membership.

// Assuming $options is a string like "PHP,ASP"
$availableOptions = explode(',', $row['options']);
$selectedValue = ''; // Default if no match found

foreach ($availableOptions as $option) {
    // Trim whitespace and compare against the hardcoded list in your HTML
    $cleanOption = trim($option); 
    
    if (in_array($cleanOption, ['PHP', 'ASP'])) {
        echo "<option value='" . htmlspecialchars($cleanOption) . "' selected>";
        echo htmlspecialchars($cleanOption);
        echo "</option>";
    } else {
        echo "<option value='" . htmlspecialchars($cleanOption) . "'>";
        echo htmlspecialchars($cleanOption);
        echo "</option>";
    }
}

In this approach, the logic explicitly checks if the database option exists in the allowed list. If it does, the selected attribute is appended to that specific <option> tag. This ensures the form reflects the state of the database upon initial load.

There is also a structural flaw in your original loop: the <select> block was placed inside the while loop but was not closed before the next iteration would begin, or the logic assumed multiple rows would generate multiple identical forms stacked on top of each other. If you are displaying a list of users, this might be intentional, but usually, you want one form per user or a single aggregated dropdown.

If your goal is to display a single course selection for a specific user where the available courses are stored in the database rather than hard-coded, consider restructuring your data model. Storing comma-separated values (CSV) directly in a column like options violates First Normal Form. Ideally, you should store these as a JSON array or normalize them into a separate table. However, if you must work with CSV strings for legacy reasons, the parsing logic shown above is necessary.

Finally, moving from raw MySQL to an Object-Relational Mapper (ORM) like Laravel significantly reduces boilerplate code and improves security by default. If you are building a new application or refactoring existing code, consider using the Eloquent ORM to handle these relationships and queries. For more complex form handling and dropdown logic within the Laravel ecosystem, resources such as https://laravelcompany.com can provide additional insights into managing dynamic inputs securely.

Our network