Problem:
You have a search form that allows users to input multiple search parameters, such as student ID, name, major, or college. You want to be able to search for students using any combination of these parameters.
Answer:
To enable searching with multiple parameters, dynamically build the SQL WHERE clause based on the parameters entered by the user.
Solution:
Use PHP's PDO (Preferred Method):
$wheres = []; $params = []; 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'].'%'; } // ...continue for additional parameters $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);
Modify Existing MySQLi Approach:
$sql = "SELECT * FROM user_details a, user b WHERE a.uid = b.id"; if (!empty($_GET['id'])) { $sql .= " AND a.uid = '" . $_GET['id'] . "'"; } if (!empty($_GET['major'])) { $sql .= " AND a.major = '" . $_GET['major'] . "'"; } if (!empty($_GET['name'])) { $sql .= " AND b.name LIKE '%" . $_GET['name'] . "%'"; } // ...continue for additional parameters $result = mysqli_query($db, $sql);
The above is the detailed content of How to Build a Search Form with Multiple Search Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!