Search Form with One or More (Multiple) Parameters

前端 未结 2 2035
遇见更好的自我
遇见更好的自我 2020-11-22 04:05

I\'ve gotten the basics down, where I\'ve created two files, the search form where a user inputs search parameters, and the results file that cranks out inputted items. For

2条回答
  •  悲哀的现实
    2020-11-22 04:21

    Build the WHERE clause dynamically. My recommended approach is to push each condition onto an array, and then use implode() to concatenate all the conditions, connecting them with AND or OR as is your preference.

    $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'].'%';
    }
    // And so on for all 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);
    

    Then display the results as in your original code.

    while ($student = $stmt->fetch()) {
        ...
    }
    

提交回复
热议问题