gpt4 book ai didi

php - 使用 PDO 将数组数据插入数据库

转载 作者:行者123 更新时间:2023-12-04 05:54:37 25 4
gpt4 key购买 nike

有人可以向我解释如何将我输出的数组数据导入到我的数据库中的行中。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com