【问题标题】:PHP & MYSQL : building a query based on multiple input values from usersPHP & MYSQL:基于用户的多个输入值构建查询
【发布时间】:2011-04-08 04:44:03
【问题描述】:

假设我三个表: *食谱 - 包含食谱 *成分 - 项目清单 * 膳食 - 膳食列表

我有一个生成如下选择的表单:

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' ))...

无需编写所有可能的组合或可能的输入(即用户从成分列表中选择,或从成分和膳食列表中选择,或从无列表中选择)?

【问题讨论】:

  • +1 表示格式精美的问题,尤其是对于新用户!您是否本质上想要“搜索条件” - 提取“所有涉及苹果的食谱”和“所有涉及香蕉的午餐食谱”等?
  • 你考虑过使用 ORM 吗?它可以让您轻松构建动态查询。
  • 不是很好。实际上很难阅读很长的一行

标签: php mysql append user-input


【解决方案1】:

有几种方法可以解决这个问题。

如果您想知道某个键是否存在于数组中,您可以使用array_key_exists

【讨论】:

  • 我不需要知道某个键是否存在,只需要知道数组是否存在,数组是否存在修改查询字符串。
【解决方案2】:

您将为可能的表和 where 块创建两个数组,然后进行收集所有内容的查询:

$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..
}

【讨论】:

  • 这很酷 - 但它不能很好地扩展,假设我可能会返回 5 个数组,它们都会修改查询......
  • 在这种情况下,创建一个数组,其中包含可接受输入 $_POST 变量的键,并具有它们的每个值:例如,'meals' => array('table'=>'meal', 'fieldname'=>'meals')。并通过一个简单的小循环循环该数组并创建您的查询。一旦你想修改你添加一个新元素到该数组。这不是更酷吗:)
【解决方案3】:

我在这里看不到“所有可能的组合或可能的输入”,而只是看到所有可能的输入。
我会检查所有可能的输入并将它们添加到查询中(如果已填写)。

【讨论】:

  • 我想我可以使用 sprintf() 并对其进行修改,但我希望有一个更具可扩展性和优雅的解决方案。
  • @Ryank 试试你的“5 个新阵列”,你会发现自动化是不可能的。每个参数都需要自己处理。并非每个条件都可以写成简单的相等检查,但其他条件可以使用betweenless thangreater thanlike 等。预定义所有条件是优雅的。不要根据这样一个愚蠢的例子来预测未来的使用情况。首先尝试使用更复杂的问题。然后才寻找解决方案
猜你喜欢
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 2013-08-02
  • 2019-11-23
相关资源
最近更新 更多