1

我有一个膳食/食谱数据库,用于创建每日膳食计划。我需要为每个meal_name创建 3 个不同的选择列表(早餐、午餐、晚餐)来显示可用的食谱选项。

到目前为止,我对上述每个都使用单独的查询,并使用单独的构建来显示每个列表的结果。

午餐查询:

  // Lunch options
  $sql = "SELECT plan_date,
    plan_meal,
    plan_recipe,
    recipe_name,
    recipe_serving_size
    FROM recipe_plans
    LEFT JOIN $table_meals ON meal_id = plan_meal    
    LEFT JOIN $table_recipes ON recipe_id = plan_recipe
    WHERE plan_date = '".$date."'
    AND meal_name = 'Lunch'
    AND plan_owner = '".$user_name."'
    ORDER BY recipe_name";
    $rc = $DB_LINK->Execute($sql);
    DBUtils::checkResult($rc, NULL, NULL, $sql);

  // Scan the rows of the SQL result
  while (!$rc->EOF) {
    $recipeList[($rc->fields['plan_recipe'])] = $rc->fields['recipe_name'] . " (" . $rc->fields['recipe_serving_size'] . ")";
    $rc->MoveNext();
  }

和构建:

// Scan the fields in the SQL result row
// Print all existing Meals, and some new ones
$minShow = 1;
$maxShow = 1;  // only build 1 while testing
for ($i = 0; $i < (isset($MealPlanObj->mealplanItems[$date]) && ($i < $maxShow) ? count($MealPlanObj->mealplanItems[$date]) : 0) + $minShow; $i++) {
  if ($i < (isset($MealPlanObj->mealplanItems[$date]) ? count($MealPlanObj->mealplanItems[$date]) : 0)) {
    // If it is an existing meal item, then set it
    $meal = $MealPlanObj->mealplanItems[$date][$i]['meal']; // meal_id
    $servings = $MealPlanObj->mealplanItems[$date][$i]['servings'];
    $recipe = $MealPlanObj->mealplanItems[$date][$i]['id']; // recipe_id
  } else {
    // It is a new one, give it blank values
    $meal = NULL;
    $servings = $defaultServings;
    $recipe = NULL;
  }
  // The HTML Code to build the select list for 'Lunch'
}

上面的代码已经为每个餐名重复了,因为那是我有限的技能离开我的地方,哈哈。

问题是:与其为 3 个条件(早餐、午餐、晚餐)中的每一个都编写单独的选择和构建语句,不如只写 1 个来输出它们?

4

1 回答 1

2

您已经使用变量来构建 SQL 查询,因此您可以只引入另一个变量,例如$meal_name. 您可以将此变量应用于您的 SQL 语句。代替:

$sql = "SELECT mplan_date,
  ...
  AND meal_name = 'Lunch'
  ...

然后你会写:

$meal_name = 'Lunch';
...
$sql = "SELECT mplan_date,
  ...
  AND meal_name = '" . mysqli_real_escape_string($meal_name) . "'
  ...

请注意 function 的使用mysqli_real_escape_string(),尽管在本示例中不是绝对必要的,但如果您不确定变量中的内容,则转义添加到 SQL 语句中的所有变量非常重要。您的示例代码易受 SQL 注入攻击。

之后,您可以更进一步,将代码打包到一个函数中:

function buildSqlQuery($meal_name, $date, $user_name)
{
  $sql = "SELECT mplan_date,
    ...
    ORDER BY recipe_name";
  return $sql;
}

$sqlForBreakfast = buildSqlQuery('Breakfast', '2000-01-01', 'teddy');
$sqlForLunch = buildSqlQuery('Lunch', '2000-01-01', 'teddy');
$sqlForDinner = buildSqlQuery('Dinner', '2000-01-01', 'teddy');
于 2012-11-24T19:25:11.253 回答