Eiolon Posted February 5, 2015 Share Posted February 5, 2015 So I have a search form that has multiple fields. All the fields are optional, however, I want users to be able to narrow things down by entering some or all if desired. What I don't know how to do is exclude a field from the search query if nothing is entered. So the form is setup as: Subject: select Topic: text Title: text Year: select Location: text Type: text Current search query and PHP: $subject = $_GET['subject']; $topic = $_GET['topic']; $title = $_GET['title']; $year = $_GET['year']; $location = $_GET['location']; $type = $_GET['type']; $sth = $dbh->prepare(" SELECT * FROM periodic WHERE SUBJECT = :subject AND TOPIC = :topic AND TITLE = :title AND YEAR = :year AND LOCATION = :location AND TYPE = :type "); $sth->bindParam(':subject', $subject); $sth->bindParam(':topic', $topic); $sth->bindParam(':title', $title); $sth->bindParam(':year', $year); $sth->bindParam(':location', $location); $sth->bindParam(':type', $type); $sth->execute(); Obviously the initial query is requiring something in each field with the AND operator and unfortunately, unless the field actually is NULL any field left blank will throw off the results. Thanks for your pointers. Link to comment https://forums.phpfreaks.com/topic/294405-exclude-fields-from-search-query-if-nothing-is-entered/ Share on other sites More sharing options...
Barand Posted February 5, 2015 Share Posted February 5, 2015 I use this method $where = array(); $whereclause = ''; if ($subject != '') { $where[] = "SUBJECT = :subject"; } if ($topic != '') { $where[] = "TOPIC = :topic"; } if ($title != '') { $where[] = "TITLE = :title"; } if (count($where) > 0) { $whereclause = " WHERE " . join(' AND ', $where); } $sql = "SELECT * FROM periodic" . $whereclause; Link to comment https://forums.phpfreaks.com/topic/294405-exclude-fields-from-search-query-if-nothing-is-entered/#findComment-1504966 Share on other sites More sharing options...
Eiolon Posted February 5, 2015 Author Share Posted February 5, 2015 Thanks, that works wonderfully! Link to comment https://forums.phpfreaks.com/topic/294405-exclude-fields-from-search-query-if-nothing-is-entered/#findComment-1504969 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.