0

I have a HTML form that people can select some or all off to search a database for member profiles.

Some of the options are:

  • Male/Female
  • Age
  • Location
  • check boxes like intentions or interests
  • etc

I need to tailor a MySQL query to meet the selection the member has chosen.

I'm asking because I built a custom search like this before and it turned into a complete mess with multiple queries depending on what was selected.

Would it be best to just build one query and have parts that are added depending on what is selected?

Does anyone have a ruff example?


Database Schema:

I have a number of tables with the related information so I would need to use joins. That said everything works on one primary key PID so it would all join on this.

1
  • How does your DB schema look? Commented Jan 9, 2014 at 22:43

2 Answers 2

2

You could do something like this:

<?php
  $whereClause = '';
  if($_GET['gender'] == 'male'){
    $whereClause .= ' AND gender = "M"';
  }
  if($_GET['age'] != ''){
    $whereClause .= ' AND age = "'.$_GET['age'].'"';
  }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

yes but as you can see I put the AND at the beggining of each string, so it depends that you have something already in the where clause like WHERE id = 1 '.$whereClause.'if you don't you could still use it but change it a little
1

I would use an array:

$where = array();
if($_GET["gender"]!=""){
  $clean = mysqli_escape_string($db, $_GET["gender"]);
  array_push($where, "gender = '$clean'");
}
// etc...
$where = implode(" AND ", $where);
$sql = "SELECT * FROM table WHERE $where";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.