Display Mysql table field values in Select box

Display Mysql table field values in Select box

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

Stefan Bogdanescu

Founder & Senior Architect

Populating Select Elements with Database Values

You want to dynamically generate a <select> box where the options are pulled directly from a MySQL table, specifically ordering them by an ascending sort order. The code snippet you provided attempts this but fails because it mixes procedural PHP logic inside a static HTML structure without actually iterating over the data within the page lifecycle.

The primary issue lies in how the loop and the database result set are handled relative to the HTML output. In your attempt, you execute a while loop that echoes values to the screen immediately. However, you then try to reference $row['Emp_id'] inside the <option> tag. By the time the browser renders that specific line of HTML, the $get result set has already been exhausted by the previous while loop, and the variable $row likely points to the last item or is undefined in the context of the static block.

To fix this, you must separate the data retrieval from the data presentation or ensure the iteration happens inside the HTML generation process. You cannot query the database once, echo all results to the screen, and then expect those variables to persist for a second, disconnected echo statement later in the code.

Correcting the Procedural Approach

If you are sticking with the procedural MySQL extension (which you are using based on your mysql_connect calls), you need to move the logic so that the loop runs while constructing the HTML string or directly within the output buffer. Here is a corrected version of your script that fetches the data and populates the select box in a single pass:

<?php
// Establish connection (Note: mysql_* functions are deprecated)
$con = @mysql_connect("localhost", "root", "root");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

$db = @mysql_select_db("Time_sheet", $con);
if (!$db) {
    die('Could not select database: ' . mysql_error());
}

// Fetch Emp_id ordered ascendingly
$get = mysql_query("SELECT DISTINCT Emp_id FROM Employee ORDER BY Emp_id ASC");

echo "<html><body><form>";
echo "<select name='employee_id'>";

if ($get && mysql_num_rows($get) > 0) {
    while($row = mysql_fetch_assoc($get)) {
        // Using htmlspecialchars is crucial for security to prevent XSS
        $empId = htmlspecialchars($row['Emp_id']); 
        echo "<option value='$empId'>$empId</option>";
    }
}

echo "</select></form></body></html>";
?>

Notice the key change: the while loop now resides strictly inside the <select> block. This ensures that the $row variable is captured and utilized immediately for each iteration, building the correct HTML structure before the loop finishes. The ORDER BY Emp_id ASC clause in your SQL query guarantees the ascending sort order you requested without needing to manipulate the data in PHP.

Modernizing with PDO or Laravel

While fixing the procedural code addresses the immediate syntax error, relying on the deprecated mysql_* extension is a significant technical debt. These functions are removed as of PHP 7.0 and pose security risks due to their susceptibility to SQL injection if not handled perfectly.

For new projects or refactoring existing ones, you should migrate to PDO or a framework like Laravel. Laravel provides elegant methods to achieve exactly what you need with built-in protection against SQL injection and automatic sorting.

In a Laravel application, you would typically use an Eloquent model or raw queries within the controller:

// In a Controller or Blade view
$employees = DB::table('Employee')
    ->select('Emp_id')
    ->distinct()
    ->orderBy('Emp_id', 'asc')
    ->get();

return view('timesheet'), compact('employees');

Then, in your Blade template:

<select name="employee_id">
    @foreach($employees as $emp)
        <option value="{{ $emp->Emp_id }}">{{ $emp->Emp_id }}</option>
    @endforeach
</select>

This approach is more readable and robust. It keeps the database interaction contained in the model or controller layer, passing a clean collection of data to the view.

Security Considerations

Regardless of whether you use procedural PHP or Laravel, never output raw user-controlled data into HTML without escaping it. In your original code, $row['Emp_id'] was echoed directly. If an Emp_id field in your database contained malicious scripts like <script>alert('XSS')</script>, they would execute in the browser when the page loads.

Always use functions like htmlspecialchars() in procedural PHP or Blade's {{ }} syntax (which automatically escapes output) to ensure that special characters are converted into HTML entities. This prevents Cross-Site Scripting (XSS) attacks, which is a critical requirement for any public-facing form.

Finally, remember that selecting distinct values (SELECT DISTINCT) is often necessary when populating dropdowns from tables with many-to-many relationships or logs where the same ID might appear multiple times. Without DISTINCT, your dropdown could contain duplicate entries, confusing the user and potentially causing logic errors in your backend processing.

Our network