I have a form that submits steps and ingredients for recipes that I am practicing with for another project. I have set the form up to submit the data in an array, but I can't get the PHP code correct to insert the data into the database. I have pasted the form layout here. The form comes up as part of another PHP page that is called when the user enters a recipe name to add to the database. I would like to have 10 separate step entries on this form if I can figure out how to insert them correctly into the database.
<form action="add_recipe2.php" method="post">
<fieldset>
<legend>Add a Recipe</legend>
<table>
<tr>
<td>Recipe Name:</td>
<td><input type="text" name="recipename" value="$recipename"></td>
</tr>
<tr>
<td>Step:</td>
<td><input type="text" name="recipe[0][step]" placeholder="1"></td>
<td>Ingredients:</td>
<td><input type="text" name="recipe[0][ingredients]" placeholder="Ingredients"></td>
</tr>
<tr>
<td>Step:</td>
<td><input type="text" name="recipe[1][step]" placeholder="2"></td>
<td>Ingredients:</td>
<td><input type="text" name="recipe[1][ingredients]" placeholder="Ingredients"></td>
</tr>
<tr>
<td>Step:</td>
<td><input type="text" name="recipe[2][step]" placeholder="3"></td>
<td>Ingredients:</td>
<td><input type="text" name="recipe[2][ingredients]" placeholder="Ingredients"></td>
</tr>
</table>
<button type="submit">Add a Recipe</button>
<button type="reset">Reset</button>
</fieldset>
</form>
This is the PHP that enters the data into the database. The problem is when I only add two records to the database the last record still inserts, but it inserts a blank line. I need a way to only add the data that is being passed from the form even if it is only one line. I have researched this a long time and this represents one of the answers that I found. However, it still does not stop inserting into the database when there is no more data from the form.
$recipename = $_REQUEST["recipename"];
$conn = mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("test");
foreach($_POST['recipe'] as $recipe) {
// Add to database
$sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES ('".$_POST['recipename']."', '".$recipe['step']."', '".$recipe['ingredients']."')";
mysql_query($sql1, $conn) or die(mysql_error());
} //end foreach
I just can't figure this out. I need help. I suspect that I have to have a way to tell how many records I am actually sending if it is not the number of form entries that exist.