简体   繁体   English

将连接到foreach循环的数组插入数据库

[英]Insert array connected to foreach loop into database

First of all, I'm kinda new to this and don't know if the title is exactly what I'm asking for so I'll apologize in forehand. 首先,我对此很陌生,不知道标题是否正是我所要的,因此我将正手道歉。 (I'm also Swedish so my English might not be perfect). (我也是瑞典人,所以我的英语可能并不完美)。 And I looked at the "similar questions" but I didn't find anything of interest so far. 我看着“类似的问题”,但到目前为止我没有发现任何有趣的东西。

I have this foreach loop: 我有这个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++;
}

and I use this to insert the connection between recipe and ingredients in my database (and I want to insert the amount and unit of that ingredient): 并且我使用它在我的数据库中插入配方和配料之间的连接(并且我想插入配料的数量和单位):

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]'")); }

it says that the variables aren't defined (the unit and amount). 它表示未定义变量(单位和数量)。 I tried to echo out the whole thing inside of the foreach loop and it worked. 我试图在foreach循环中回显整个事情,并且它起作用了。 So I guess that the extension with [$i] is right, but I don't know how to use it for the INPUT. 因此,我猜想带有[$ i]的扩展名是正确的,但我不知道如何将其用于INPUT。

echo $amount[$i].' '.$unit[$i].' - '.$ingredient;

So the connection between the recipe(id) and the ingredients(id) are working just fine, but the amount and units doesn't wanna get into the database. 因此,配方(id)和配料(id)之间的连接工作正常,但是数量和单位都不想进入数据库。

How am I suppose to insert those arrays into the database? 我应该如何将这些数组插入数据库?

Do you need any more information? 您是否需要更多信息?

Change your if statement to this: 将您的if语句更改为此:

if($ingredient_id != false) {
    insertRecipeIngredient($link, $recipe_id, $ingredient_id, $unit, $amount, $i);
}

And change that function to accept the $unit , $amount , and $i parameters 并更改该函数以接受$unit$amount$i参数

function insertRecipeIngredient($link, $recipe_id, $ingredient_id, $unit, $amount, $i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM