Home > Backend Development > PHP Tutorial > How to Build a Dynamic Search Form with Multiple Parameters in PHP?

How to Build a Dynamic Search Form with Multiple Parameters in PHP?

Susan Sarandon
Release: 2024-12-26 19:44:10
Original
681 people have browsed it

How to Build a Dynamic Search Form with Multiple Parameters in PHP?

Search Form with One or More (Multiple) Parameters

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&amp;id='.$student['id'].'">
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template