How to filter an HTML table based on drop down selected value
You have a static list of rows populated from a database, but you want the user to interact with the page by selecting a status from a dropdown menu and immediately seeing only the matching rows. The core challenge here isn't just hiding elements; it's ensuring that every time the selection changes, your application logic correctly queries the data source or re-renders the table based on that specific filter value.
The most robust approach in a server-side rendered environment like PHP is to pass the selected value back to the database query itself. If you attempt to hide rows using JavaScript alone without updating the underlying data, you risk showing stale data if the user navigates away and returns, or if the page is cached. By moving the filtering logic into the SQL query, you ensure that only relevant records are fetched from the database in the first place.
Passing the Filter Value to the Query
First, you need to capture the state of your dropdown. In your HTML structure, the status filter is inside a form:
<form method="post" action="activeInactive.php">
<!-- Dropdown for filtering -->
<select name="status_filter" class="form-control">
<option value="">Any</option>
<option value="Completed">Completed</option>
<option value="In Progress">In Progress</option>
<option value="To Run">To Run</option>
</select>
</form>
Notice the name attribute on the select element. This allows PHP to retrieve the user's choice via $_POST['status_filter'].
Next, modify your database connection and query in activeInactive.php. Instead of fetching all rows with a simple loop like $tests_under_user, you must conditionally append a WHERE clause based on the input. It is crucial to handle the "Any" option carefully. If the user selects "Any", you should not add a filter condition at all, or you might inadvertently exclude all rows if your logic defaults to checking for equality without an OR condition.
Here is a safer pattern for constructing that query:
$statusFilter = $_POST['status_filter'] ?? '';
$sql = "SELECT * FROM tests WHERE 1=1"; // Start with a neutral condition
if (!empty($statusFilter)) {
// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM tests WHERE status = ?");
$stmt->execute([$statusFilter]);
$tests_under_user = $stmt->fetchAll();
} else {
// Fetch all rows if no specific filter is selected
$stmt = $pdo->query("SELECT * FROM tests");
$tests_under_user = $stmt->fetchAll();
}
while($row = mysqli_fetch_array($tests_under_user)) {
echo '<td width=250px title="' . htmlspecialchars($row['name']) . '">' . $row['name'] . '</td>';
// ... rest of your table row generation
}
Handling the "Any" Option
A common pitfall in filtering logic is how to handle the default selection. In your dropdown, "Any" acts as a wildcard. If you set the initial value of the select input to match the database default (e.g., In Progress), loading the page will immediately hide rows that are marked "To Do".
To avoid this jarring user experience, ensure the dropdown's value attribute matches what your backend expects for "no filter." If your backend treats an empty string as "show all," set the first <option> to:
<option value="" selected>Any</option>
This ensures that on the initial page load, if no POST data exists (or the form hasn't been submitted yet), the query retrieves the full dataset. When the user submits the form with a specific status, the $_POST variable will contain that status string, triggering the filtered query.
Scalability Considerations
If you decide to move away from server-side rendering to a client-side approach using JavaScript frameworks like Vue or React, the logic shifts slightly. You would fetch all data once and then use .filter() in JavaScript to toggle visibility based on the dropdown change event. However, this requires keeping the full dataset in memory. For large tables, this can lead to performance degradation.
The server-side method described above is generally preferred for standard PHP applications because it scales with database size regardless of how many filters a user applies. It also keeps your logic centralized; if you add more filters (e.g., date range or creator), you simply extend the SQL WHERE clause rather than rewriting complex JavaScript logic.
If you are building this within a Laravel project, consider using Eloquent scopes to keep your code clean and reusable. You can define a scope that accepts the status parameter, allowing you to write Test::scopeFilterStatus($_POST['status_filter']) without cluttering your controller with conditional SQL concatenation. This pattern promotes maintainability as your application grows.