我有一个表单,提交我正在为另一个项目练习的食谱的步骤和成分。我已经将表单设置为在数组中提交数据,但是我无法正确地将PHP代码插入到数据库中。我在这里粘贴了表单布局。该表单作为另一个PHP页面的一部分出现,该页面在用户输入要添加到数据库的配方名称时调用。如果我能弄清楚如何将它们正确地插入到数据库中,我想在此表单上有10个单独的步骤条目。
<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>
这是将数据输入数据库的PHP。问题是当我只向数据库添加两条记录时,最后一条记录仍会插入,但它会插入一个空白行。我需要一种方法来只添加从表单传递的数据,即使它只是一行。我已经研究了很长时间,这代表了我找到的答案之一。但是,当表单中没有更多数据时,它仍然不会停止插入数据库。
$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
我无法弄清楚这一点。我需要帮助。我怀疑如果不是存在的表单条目数,我必须有办法告诉我实际发送了多少条记录。
答案 0 :(得分:2)
在查询数组组件中的值之前,您需要测试它们是否已填入。此外,您必须使用mysql_real_escape_string()
:
$recipename = mysql_real_escape_string($_POST['recipename']);
foreach($_POST['recipe'] as $recipe) {
// Only insert if step is non-empty.
if (!empty($recipe['step']) {
// Add to database
// Escape against SQL injection
$recipe['step'] = mysql_real_escape_string($recipe['step'];
$recipe['ingredients'] = mysql_real_escape_string($recipe['ingredients'];
$sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES ('".$recipename."', '".$recipe['step']."', '".$recipe['ingredients']."')";
mysql_query($sql1, $conn) or die(mysql_error());
}
}
答案 1 :(得分:0)
事实是,即使用户没有填写食谱[3]表格中的信息,仍然会提交空值。
在插入数据库之前,您必须验证数据:
function isValidRecipe($recipe){
// returns true if ingredients and step are not empty
return !(empty($recipe['ingredients']) || empty($recipe['step']));
}
foreach($_POST['recipe'] as $recipe) {
if (isValidRecipe($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());
}
}
请注意,这是最低限度的验证,您应该更彻底地检查所有内容。