假设我有三个表: * 食谱 - 包含食谱 * 成分 - 项目列表 * 膳食 - 膳食 list
我有一个生成如下选择的表单:
Choose what ingredients you have:
- apples
- bananas
- cherries
Choose the meal this is for:
- breakfast
- lunch
- dinner
我希望用户能够从以上任何一个中选择一个或都不选择,即他们可以选择苹果或樱桃或(香蕉 && 午餐)
当我查询 MySQL 时,我的查询大致是
select recipes.* from recipes
或
select recipes.* from recipes, ingredients
where recipes.id= ingredients.id and ingredients.list in ('apple');
或
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_array(ingredients) 将表(ingredients)添加到查询中,并在最后加上(".ingredients.list in('apple' ))...
无需写下所有可能的组合或可能的输入(即用户从配料列表中选择,或从配料和膳食列表中选择,或从无列表中选择)?
最佳答案
有几种方法可以解决这个问题。
如果你想知道一个键是否存在于数组中,你可以使用 array_key_exists
关于PHP & MySQL : building a query based on multiple input values from users,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3641850/