如何使用PHP从动态增加的表单字段中将信息保存到数据库?

时间:2011-08-22 03:40:43

标签: php jquery mysql codeigniter

我正在尝试制作一个关于食谱的程序。用户必须能够添加更多成分,如果他/她愿意,同时他也可以删除字段。

我在考虑将多个字段命名为什么,以及如何获取值并将其插入数据库?

感谢任何帮助。提前谢谢。

3 个答案:

答案 0 :(得分:0)

在HTML中的字段名称末尾使用方括号,它们将在PHP中显示为数组:

<input type="text" name="ingredients[]" value="Chicken" />
<input type="text" name="ingredients[]" value="Mushroom" />
<input type="text" name="ingredients[]" value="Cream" />

然后这将提供一个请求变量(假设您在这种情况下使用POST),以便请求数组(即$ _POST)出现在PHP中(即,如果您调用var_dump):

array(1) {
  ["ingredients"]=>
  array(3) {
    [0]=>
    string(7) "Chicken"
    [1]=>
    string(8) "Mushroom"
    [2]=>
    string(5) "Cream"
  }
}

答案 1 :(得分:0)

我假设您的应用程序数据库中有一个表来存储配方详细信息,例如配方名称,照片等。此表中的每个条目也都有一个名为RecipeId的主键。

由于配方可以有多种成分,因此这里有一对多关系。因此,您必须使用外键RecipeId创建另一个表来存储配料详细信息。

现在使用相应的RecipeId将成分详细信息插入到这个新表中。

如果您认为食谱可能有多个指示或烹饪说明,则同样适用于指导和烹饪说明。

希望这会对你有所帮助。

实现:

在客户端,您已添加了所需的html和javascript以添加多个条目。

您可以将成分对象数组发送到您的php页面。

E.g

$.ajax({
   url: "CreateRecipe.php",
   data: { recipeName: "myRecipe", 
           ingredients: [ { name: "", amount: "", unit: "" },
                          { name: "", amount: "", unit: "" } ],
           directions: "",
           cookingInstructions: "" }
  success: function(){ }
});

答案 2 :(得分:0)

您可以至少有五列(ID,名称,成分,方向,说明)来执行此类任务。虽然以明显的方式保存id和名称,但对于其余三列,您需要将其保存为序列化数组。因此,您可以为该三列的每个部分创建任意数量的字段,如此...

<input name="ingredients[]" ... />
<input name="ingredients[]" ... />
<input name="ingredients[]" ... />

和其他两个字段,然后在将其保存为列值

之前将其传输到序列化数据中
// You can do this before save the value into your database
$ingredients = serialize($_POST['ingredients']);

// While you retrieve the value from your database, unserialize it to get your array back
$ingredients = unserialize($row['ingredients']);