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. Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted February 5, 2015 Solution Share Posted February 5, 2015 (edited) 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; Edited February 5, 2015 by Barand Quote Link to comment Share on other sites More sharing options...
Eiolon Posted February 5, 2015 Author Share Posted February 5, 2015 Thanks, that works wonderfully! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.