Search Form with One or More (Multiple) Parameters
Problem:
In a previous implementation of a search form, only one parameter could be used at a time. The goal is to modify this form to allow users to input one or more parameters and receive the corresponding search results.
Solution:
To achieve this, we'll modify the PHP code to dynamically build the WHERE clause based on the input parameters.
Modified search.php:
<?php $wheres = []; $params = []; if (!empty($_POST['id']) && isset($_POST['id'])) { $wheres[] = 'a.uid = :uid'; $params[':uid'] = $_POST['id']; } if (!empty($_POST['major']) && isset($_POST['major'])) { $wheres[] = 'a.major = :major'; $params[':major'] = $_POST['major']; } if (!empty($_POST['college']) && isset($_POST['college'])) { $wheres[] = 'a.college = :college'; $params[':college'] = $_POST['college']; } if (!empty($_POST['name']) && isset($_POST['name'])) { $wheres[] = 'b.name LIKE :name'; $params[':name'] = '%' . $_POST['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); // Display the results as in the original code
Explanation:
By utilizing this approach, users can now input multiple parameters and obtain results based on all specified criteria.
The above is the detailed content of How Can I Modify a Search Form to Accept Multiple Search Parameters?. For more information, please follow other related articles on the PHP Chinese website!