首先,我对此有点陌生,不知道标题是否正是我所要求的,所以我会预先道歉。(我也是瑞典人,所以我的英语可能并不完美)。我看了"类似的问题",但到目前为止我没有找到任何感兴趣的东西。
我有这个 foreach 循环:
$i = 0;
foreach($ingredients as $ingredient) {
$ingredient_id = getIngredientId ($link, $ingredient);
if($ingredient_id != false) {
insertRecipeIngredient($link, $recipe_id, $ingredient_id, $unit, $amount);
} else {
$ingredient_id = insertIngredient($link, $ingredient);
}
$i++;
}
我用它来插入数据库中食谱和成分之间的联系(我想插入该成分的数量和单位):
function insertRecipeIngredient($link, $recipe_id, $ingredient_id) {
mysqli_query($link, "INSERT INTO recipe_ingredients (recipe_id, ingredient_id, unit,
amount) VALUES ('$recipe_id','$ingredient_id', '$unit[$i]', '$amount[$i]'")); }
它说变量没有定义(单位和数量)。我试图在foreach循环中回声整个事情,它奏效了。所以我想带有 [$i] 的扩展是正确的,但我不知道如何将它用于 INPUT。
echo $amount[$i].' '.$unit[$i].' - '.$ingredient;
因此,recipe(id)和成分(id)之间的连接工作正常,但是数量和单位不想进入数据库。
我应该如何将这些数组插入数据库?
您需要更多信息吗?
将 if 语句更改为:
if($ingredient_id != false) {
insertRecipeIngredient($link, $recipe_id, $ingredient_id, $unit, $amount, $i);
}
并更改该函数以接受$unit
、$amount
和 $i
参数
function insertRecipeIngredient($link, $recipe_id, $ingredient_id, $unit, $amount, $i)