有人可以向我解释如何将我输出的数组数据导入我的数据库中的行。
HTML
<form id="AddRecipeForm" method="post" action="includes/add-recipe.php" class="form-inline">
<input type="text" name="recipe[ingredient][1]" class="input-large" placeholder="Title 1"><input type="text" name="recipe[quantity][1]" class="input-large" placeholder="Quantity 1"><br /><br />
<input type="text" name="recipe[ingredient][2]" class="input-large" placeholder="Title 2"><input type="text" name="recipe[quantity][2]" class="input-large" placeholder="Quantity 2"><br /><br />
<input type="text" name="recipe[ingredient][3]" class="input-large" placeholder="Title 3"><input type="text" name="recipe[quantity][3]" class="input-large" placeholder="Quantity 3"><br /><br />
<button type="submit" class="btn">Add Recipe</button>
</form>
这是传递给php表单:
foreach($_POST['recipe'] as $key=>$value)
{
}
print_r($_POST);
并输出以下数组:
Array (
[recipe] => Array (
[ingredient] => Array (
[1] => eggs
[2] => milk
[3] => flour
) [quantity] => Array (
[1] => 12
[2] => 13
[3] => 14
)
)
)
我需要将每个成分和数量导入我的数据库表中的新行。我正在使用PDO连接到我的数据库,但我不确定如何将数组中的数据插入到我的数据库中的行中。
感谢。
答案 0 :(得分:2)
好吧,我会把我的形状结构有点不同,所以你把成分组装成他们自己的阵列,但是你得到了结果:
$db = new PDO($dsn, $user, $pass);
$stmt = $db->prepare('INSERT INTO ingredient (name, quantity) VALUES (?,?)');
// youll want to verify that both arrays have the same number of elements before doing this
// as part of your validation
$ingredients = array_combine($_POST['recipe']['ingredient'], $_POST['recipe']['quantity']);
$errors = array();
foreach($ingredients as $name => $quantity)
{
try {
$stmt->execute(array($name, $quantity));
} catch (PDOException $e) {
$errors[] = array(
'message' => "Could not insert \"$name\", \"$quantity\".",
'error' => $e
}
}
if(!empty($errors)) {
//do something?
}
答案 1 :(得分:1)
没有错误检查的简单示例:
<?php
$dbc = new PDO(/* ... */);
$stmt = $dbc->prepare("INSERT INTO tbl(ingredient,quantity) VALUES(:ingredient,:quantity);");
$numIngredients = count($_POST['recipe']['ingredient']);
for ($i=1; $i <= $numIngredients; $i++) {
$stmt->execute(array(
':ingredient' => $_POST['recipe']['ingredient'][$i],
':quantity' => $_POST['recipe']['quantity'][$i]
));
}
?>
请注意,通常您应该从0开始计算索引,如果您只是编写recipe[ingredient][]
,PHP将自动创建索引。
答案 2 :(得分:0)
我认为您的问题是$_POST
数组的格式。你有:
[recipe][ingredient][...] and
[recipe][quantity][...]
但是,这不是数据库的结构,它按行和列组织它:
[recipe][...][ingredient, quantity]
您可以看到[...]
如何移动。您需要将数组格式映射到数据库格式。使用foreach
:
$recipes = array(); # Zero rows to insert we start with.
$formRecipes = $_POST['recipe']; # The form recipes are located here.
# The [...] part is in ingredient:
foreach ($formRecipes['ingredient'] as $index => $ingredient)
{
# the [...] part is $index now
$recipes[$index]['ingredient'] = $ingredient;
$recipes[$index]['quantity'] = $formRecipes['quantity'][$index];
}
运行完毕后,使用print_r
验证一切正常:
print_r($recipes);
您现在可以使用$recipes
数组将数据插入到每行的数据库中(我假设您知道如何执行插入SQL查询,因此我不会将其放入答案中)。