有人可以向我解释一下如何将我输出的数组数据导入到数据库的行中吗?
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 连接到我的数据库,但我不确定如何将数组中的数据插入到数据库的行中。
谢谢。
最佳答案
好吧,我会稍微不同地构建我的表单,这样你就可以将成分组装为自己的数组,但使用你拥有的结构:
$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?
}
关于php - 使用 PDO 将数组数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9658707/