开发者

How to save information to a database from a dynamically increasing number of form fields using PHP?

I am trying to make a program about recipes.开发者_开发知识库 The user would have to be able to add more ingredients if he/she wishes to and at the same he can also remove the fields.

I was thinking on what will I name the multiple field and how will I be able to get the values and insert them into the database?

Any help is appreciated. Thanks in advance.


Use square brackets at the end of your field names in HTML and they will appear to PHP as an array:

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

This will then provide a request variable (let's assume you use POST for this scenario) so that the request array (i.e. $_POST) appears to PHP (i.e. if you call var_dump) as:

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


I am assuming you have a table in your application database to store the recipe details like Recipe name, photo etc. Every entry in this table will also have a primary key called RecipeId.

Since a recipe can have multiple ingredients there is a one to many relation here. So you have to create another table to store the ingredient details with a foreign key RecipeId.

Now insert the ingredient details into this new table with the corresponding RecipeId.

Same applies to direction and cooking instruction if you think there can be multiple directions or cooking instructions for a recipe.

Hope this helps you.

Implementation:

On the client side you have already added the required html and javascript to add multiple entries.

You can send the array of ingredients object to your php page.

E.g

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


You can have at least five columns (id, name, Ingredients, Directions, Instruction) to do that such task. And while you save id and name in an obvious way, for the rest three column, you need to save it as serialized array. So you can have as many fields as you want for each section of that three column, like so..

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

and other two field, then transfer it into a serialized data before you save it as a column value

// 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']);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜