【问题标题】:PHP add value to database depending on the amount of inputs for this tablePHP 根据该表的输入量向数据库添加值
【发布时间】:2020-01-29 16:29:15
【问题描述】:

对不起,我很难解释。我有一个食谱数据库。在这个数据库中,我有一个成分表、一个食谱表和一个它们链接的 recipeIngredients 表。

我拥有的基本表单将输入配方名称和输入成分。这个输入栏旁边会有一个加号按钮,如果用户单击加号按钮,将出现另一个输入框,其中将输入另一种成分。

到目前为止,我的代码仅在我只有一种配方成分被发送到数据库时才有效。当我点击提交时,有没有办法让这个表单将多种成分发送到成分表?

这是我的 html 表单:

        <form class="recipe-form" method="post">
                   <div class="form-group col-md-12">
                       <label>Name :</label>
                       <input class="form-control" type="text" name="name">
                   </div>

                   <div class="form-group col-md-12">
                       <label>ingredients :</label>
                       <input class="form-control" type="text" name="ingredientName" />
                   </div>
                       <button type="submit" name="submit" value=" Submit">
                           Login</button>
       </form>

这是我为输入一种成分所做的 php。我完全不确定如何处理这个以允许用户在成分表中输入多个值。

        if(isset($_POST["submit"])) 
{
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $ingredientName = mysqli_real_escape_string($conn, $_POST['ingredientName']);
    $sql1 = ("INSERT INTO recipes(recipe_ID, user_ID, name) VALUES (NULL, '117', '$name')");
    mysqli_query($conn, $sql1);
    $recipe_ID = mysqli_insert_id($conn);
    $sql2 = ("INSERT INTO ingredients(ingredient_ID, name) VALUES (NULL, '$ingredientName')");
    mysqli_query($conn, $sql2);
    $ingredient_ID = mysqli_insert_id($conn);
    $sql3 = ("INSERT INTO recipeingredient(recipe_ID, ingredient_ID) VALUES('$recipe_ID', '$ingredient_ID')");
    mysqli_query($conn, $sql3);

【问题讨论】:

  • “到目前为止,我的代码仅在我只有一种配方成分被发送到数据库时才有效。有没有办法让这种形式将多种成分发送到成分表当我点击提交时?” - 你到底是什么意思?您想要更多输入还是处理一个可以处理多个值的输入?
  • 对不起。目前,表单有一个成分输入。因此,如果我有一个“加号按钮”,它将另一个输入字段添加到成分的表单中(现在有两个成分字段),那么我将如何将这两种成分添加到数据库中,而不仅仅是一个。这是否更好地解释了它?
  • “所以,如果我有一个“加号按钮”,它会在成分表单中添加另一个输入字段” - 你需要为此使用 Javascript,而我我不是这个人。
  • name="ingredientName[]" 在每个成分字段上将其转换为值数组,您将在 PHP 中的成分名称上使用 foreach 来插入值
  • @Shauna 有人在下面提交了答案,请参阅。

标签: php sql database input


【解决方案1】:

这是你可以做的,

<form class="recipe-form" method="post">
<div class="form-group col-md-12">
    <label>Name :</label>
    <input class="form-control" type="text" name="name">
</div>

<div class="form-group col-md-12">
    <label>ingredients :</label>
    <input class="form-control" type="text" name="name[ingredients][]" />
</div>
<button type="submit" name="submit" value=" Submit">Login</button>

在您的 php 中,您现在应该有一个数组,您可以循环并创建一个新的信息数组并插入到数据库中。

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 2016-07-13
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多