Dynamic drop down list using html and php

Dynamic drop down list using html and php

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

Stefan Bogdanescu

Founder & Senior Architect

Dynamic Drop Down List using html and php

Building a cascading dropdown list—where selecting a value in one field updates another—is a classic requirement in web forms. The challenge lies in synchronizing client-side state (what the user sees) with server-side logic (the database query). The source material highlights a common stumbling block: how to access the $_POST or $_GET data from the first two selects to drive the third, specifically when dealing with older PHP syntax and basic HTML.

The fundamental mechanism is straightforward but often misunderstood by beginners. You cannot directly pass values from one <select> element to another via standard HTML attributes. Instead, you must bridge the gap using either JavaScript or a page reload strategy. The source code example suggests using onchange="run()", which implies an asynchronous approach using client-side scripting. This is the most responsive method, but it requires understanding how to read form values and send them back to the server.

The Client-Side Bridge: Using JavaScript

The provided snippet attempts to use document.getElementById("id").value inside a PHP context, which is a critical conceptual error. PHP runs on the server before the HTML reaches the browser; it cannot execute document.getElementById. To fix this, you must write a small JavaScript function that executes when the user changes the department or hire type.

Here is how you structure the interaction:

<form id="form1" method="post" action="">
    Department: 
    <select id="department" name="department" onchange="updateEmployees()">
        <option value="biology">Biology</option>
        <option value="chemistry">Chemistry</option>
        <option value="physics">Physics</option>
        <option value="math">Math</option>
    </select><br><br>

    Type Hire: 
    <select id="type_hire" name="type_hire" onchange="updateEmployees()">
        <option value="internal">Internal</option>
        <option value="external">External</option>
    </select><br><br>

    List of Employees:
    <select name='employees'>
        <option value="">-- Select --</option>
        <!-- Options populated dynamically -->
    </select>
</form>

<script>
function updateEmployees() {
    // 1. Get values from the DOM
    var dept = document.getElementById('department').value;
    var hireType = document.getElementById('type_hire').value;

    if (!dept || !hireType) return; // Prevent query if empty

    // 2. Send data to the server via AJAX (Fetch API)
    fetch('load_employees.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ department: dept, type_hire: hireType })
    })
    .then(response => response.json())
    .then(data => {
        // 3. Clear existing options and rebuild the list
        var selectElement = document.querySelector('select[name="employees"]');
        selectElement.innerHTML = '<option value="">-- Select --</option>';

        data.forEach(function(emp) {
            var option = document.createElement('option');
            option.value = emp.name;
            option.textContent = emp.name;
            selectElement.appendChild(option);
        });
    })
    .catch(error => console.error('Error:', error));
}
</script>

In this implementation, the updateEmployees function reads the current values from the DOM. It then uses the Fetch API to send these parameters to a backend script (load_employees.php). This separates concerns: the frontend handles UI logic, while the backend handles data retrieval.

The Server-Side Logic: PHP Query Handling

The backend script receives the JSON payload and constructs the SQL query using the provided values. It is crucial to note that the source material's original SQL query contains significant security vulnerabilities. Specifically, it attempts to select name from a table called usuario (likely a typo for Employees_hired) but joins conditions on contrasena (password) and department.

For a functional dynamic list, the query should filter by department and contract type, not password fields. Here is a secure implementation using prepared statements:

load_employees.php

<?php
// Establish connection (using PDO for security and modern standards)
$host = "localhost";
$db   = "employees_hired"; // Assuming this is the DB name containing the table
$user = "root";
$pass = "";
$charset = "utf8mb4";

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

// Receive POST data
$input = json_decode(file_get_contents('php://input'), true);
$department = $input['department'];
$type_hire = $input['type_hire'];

// Construct query with placeholders to prevent SQL Injection
$stmt = $pdo->prepare("SELECT name FROM Employees_hired WHERE department = :dept AND type_contract = :contract");
$stmt->execute([':dept' => $department, ':contract' => $type_hire]);
$employees = $stmt->fetchAll();

// Return JSON response
header('Content-Type: application/json');
echo json_encode($employees);
?>

Trade-offs and Best Practices

The source material asks if this is possible with only HTML and PHP. The answer is technically yes, but not in a dynamic way without reloading the page. A purely server-side approach would require submitting the form for every dropdown change:

<form method="post" action="">
    <select name="department">...</select>
    <select name="type_hire">...</select>
    <select name="employees">
        <?php
        // This only works if the form is submitted via POST
        $dept = $_POST['department'] ?? ''; 
        $hire = $_POST['type_hire'] ?? ''; 
        
        // Query logic here...
        ?>
    </select>
</form>

This creates a "page flicker" every time the user changes their mind, providing a poor user experience. The AJAX approach described earlier avoids this by keeping the page intact. However, it does require learning basic JavaScript concepts like DOM manipulation and asynchronous requests. If your goal is strictly static HTML/PHP without JavaScript knowledge, you must accept the limitation of page reloads or pre-loading all data into the third dropdown (which defeats the purpose of filtering).

For modern applications, integrating a framework like Laravel simplifies this significantly by managing routing, JSON responses, and CSRF protection automatically. Resources like https://laravelcompany.com can provide deeper insights into building robust dynamic forms within such frameworks.

Our network