0

I have an advanced search with 4 fields, only one name_first is mandatory

There are many variations of search as the other fields are not mandatory so I need a select statement that only selects the fields that have been populated, but there are so many variations

I have tried the below script but it does not show the correct information (I think it is completely wrong?!)

$name_first=$_GET["name_first"]; $status=$_GET["status"]; $type=$_GET["type"]; $manstaff=$_GET["manstaff"]; $result401=mysql_query("SELECT * FROM `hr_employees` WHERE (name_first LIKE '$name_first%') AND (status LIKE '$status%') AND (manages_staff LIKE '$manstaff%');")or die('Error' . mysql_error()); 

Any ideas what the script above should be? Basically if the field isnt completed it doesnt need to search for it?

11
  • 1
    change this $name_first% to this %$name_first% Commented Jan 25, 2016 at 21:15
  • Thanks, however it still doesnt cover all the variations of search? If I complete a field EG status to something that doesnt match the name_first it still brings up a result based on name_first if that makes sense? Commented Jan 25, 2016 at 21:17
  • 1
    why you use AND instead of OR ?? any reason ?? and why name_first IS NULL ?? Commented Jan 25, 2016 at 21:18
  • As if all the fields are completed it would need to be AND? Commented Jan 25, 2016 at 21:19
  • So in worst case if there is only first variable is set then ?? Commented Jan 25, 2016 at 21:20

1 Answer 1

0

First define your SQL with only the required criteria

$sql = "SELECT * FROM `hr_employees` WHERE (name_first LIKE '$name_first%')"; 

then add the optional criteria... optionally

if ($status) { $sql .= " AND (status LIKE '$status%') "; } if ($manstaff) { $sql .= " AND (manages_staff LIKE '$manstaff%')"; } $result401=mysql_query($sql) or die ('Error' . mysql_error()); 

Incidentally, please consider updating your code to avoid using the deprecated mysql functions, and keep in mind that concatenating variables into your SQL like this makes your code vulnerable to SQL injection.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.