When creating a search form that allows users to input multiple parameters, it's important to consider how the search results will be filtered.
In the provided example, the search form has separate input fields for ID, name, major, and college. The results.php file then uses individual if/elseif statements to handle each of these parameters separately.
However, to allow users to input one or more parameters, a more dynamic approach is needed. This can be achieved by building the WHERE clause for the SQL query dynamically based on the parameters that were entered.
Here's a revised version of the results.php file that demonstrates this approach:
<?php $wheres = array(); $params = array(); if (!empty($_GET['id'])) { $wheres[] = 'a.uid = :uid'; $params[':uid'] = $_GET['id']; } if (!empty($_GET['major'])) { $wheres[] = 'a.major = :major'; $params[':major'] = $_GET['major']; } if (!empty($_GET['name'])) { $wheres[] = 'b.name LIKE :name'; $params[':name'] = '%'.$_GET['name'].'%'; } $sql = "SELECT * FROM user_details AS a JOIN user AS b ON a.uid = b.id"; if (!empty($wheres)) { $sql .= " WHERE " . implode(' AND ', $wheres); } $stmt = $db->prepare($sql); $stmt->execute($params); while ($student = $stmt->fetch()) { echo ' <tr> <td>'.$student['uid'].'</td> <td>'.$student['name'].'</td> <td>'.$student['major'].'</td> <td>'.$student['college'].'</td> <td><a href="?m=profile&id='.$student['id'].'">
This code dynamically builds the WHERE clause based on the parameters that were entered. If the user only enters a name, then the query will only filter by name. If the user enters both a name and a major, then the query will filter by both parameters.
This approach allows for a more flexible and user-friendly search experience.
The above is the detailed content of How to Build a Dynamic Search Form with Multiple Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!