简体   繁体   中英

PHP & MYSQL : building a query based on multiple input values from users

Hypothetically I three tables: * recipes - contains recipes * ingredients - list of items * meals - list of meals

I have a form that generates a selection like:

Choose what ingredients you have:
- apples
- bananas 
- cherries

Choose the meal this is for:
- breakfast
- lunch
- dinner

I want the user to be able to choose from either or none of the above, ie they may choose apples OR cherries OR (bananas && lunch)

When I query MySQL my query is roughly

select recipes.* from recipes

or

select recipes.* from recipes, ingredients 
where recipes.id= ingredients.id and ingredients.list in ('apple');

or

select recipes.* 
from recipes, ingredients, meal 
where recipes.id= ingredients.id 
      and ingredients.list 
      and ingredients.id = meals.id 
      and ingredients.list ('apple') 
      and meals.list in ('lunch');

Is there a nice way of saying (in PHP) if this array exists (ie is_array(ingredients) add to the query the table (ingredients) and at the end tack on (".ingredients.list in ('apple'))...

without having to write all the possible combinations or possible inputs (ie the user's selected from the ingredients list, or from the ingredients and meals list, or from no lists)?

There are several approaches to tackle this.

If you want to know if a key exists in an array you can use array_key_exists

You would create two arrays for possible tables and where chunks, then make the query that gathers everything:

$wheres=array();
$tables=array();
if(isset($_POST['ingredients'])) {
  $tables[]='ingredients';

  $ingredients=array_map('mysqL_real_escape_string', $_POST['ingredients']);
  $wheres[]='ingredients.list IN (\''. join(', ', $ingredients). '\')';
  //add other wheres if you want
}
if(isset($_POST['meals'])) {
  $tables[]='meal';

  $meals=array_map('mysqL_real_escape_string', $_POST['meals']);
  $wheres[]='meals.list IN (\''. join(', ', $ingredients). '\')';
  //add other wheres if you want
}

if(!$tables) {
  echo 'You have not chose anything!';
} else {
  $query = 'SELECT * FROM '. join(',', $tables). ' WHERE '. join(' AND ', $wheres);
  //do other stuff..
}

I see no "all the possible combinations or possible inputs" here but just all possible inputs.
I'd check all possible inputs and add them to the query if filled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM