PHP 与MYSQL:根据用户的多个输入值构建查询
假设我有三个表: * 食谱 - 包含食谱 * 成分 - 物品清单 * 餐食 - 餐食列表
我有一个生成选择的表单,例如:
Choose what ingredients you have:
- apples
- bananas
- cherries
Choose the meal this is for:
- breakfast
- lunch
- dinner
我希望用户能够从以上任一选项中进行选择,或者都不进行选择,即他们可以选择苹果或樱桃或(香蕉和午餐
)我查询 MySQL 我的查询大致是
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');
是否有一个很好的方式来表示(在 PHP 中)该数组是否存在(即 is_array(ingredients) 将表(成分)添加到查询中,并在最后添加 (".ingredients.列表在('苹果'))...
而不必编写所有可能的组合或可能的输入(即用户从成分列表中选择,或从成分和膳食列表中选择,或从无列表中选择)?
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, i.e 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 (i.e. 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 (i.e. the user's selected from the ingredients list, or from the ingredients and meals list, or from no lists)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有几种方法可以解决这个问题。
如果你想知道数组中是否存在某个键,可以使用 array_key_exists
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:
我在这里没有看到“所有可能的组合或可能的输入”,而只是所有可能的输入。
我会检查所有可能的输入并将它们添加到查询(如果已填充)。
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.