Home > Backend Development > PHP Tutorial > How Can I Modify a Search Form to Accept Multiple Search Parameters?

How Can I Modify a Search Form to Accept Multiple Search Parameters?

DDD
Release: 2025-01-03 18:24:40
Original
1015 people have browsed it

How Can I Modify a Search Form to Accept Multiple Search Parameters?

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
Copy after login

Explanation:

  1. Initialize empty arrays for the WHERE clause conditions and parameters.
  2. Check for each input parameter and add the corresponding condition and parameter to the arrays.
  3. Build the SQL query by dynamically including the combined WHERE clause conditions.
  4. Prepare and execute the SQL statement using PDO with named parameters.
  5. Display the search results as in the original implementation.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template