user1105192
user1105192

Reputation: 412

PHP MySQL + Create Search Query Based off Form Selection

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:

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.

Upvotes: 0

Views: 168

Answers (2)

rybo111
rybo111

Reputation: 12598

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";

Upvotes: 1

rod_torres
rod_torres

Reputation: 346

You could do something like this:

<?php
  $whereClause = '';
  if($_GET['gender'] == 'male'){
    $whereClause .= ' AND gender = "M"';
  }
  if($_GET['age'] != ''){
    $whereClause .= ' AND age = "'.$_GET['age'].'"';
  }
?>

Upvotes: 2

Related Questions