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

标签 php html arrays forms pdo

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

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/

相关文章:

php - 为图像的各个部分着色

javascript - 如何使用发布请求打开新选项卡?

javascript - 将 "getElementById"组合在一起?

c++ - 为什么我的函数打印地址而不是数组的内容?

javascript - AngularJS 获取 JSON 数组中特定项的长度

c++ - 在同一内存地址不需要的对象创建

php - 如何计算以天为单位的持续时间?

php - mysql显示所有行的计算平均值

javascript - js中添加两个变量

javascript - 如何使我正在创建的灯箱仅在我单击的 div 上打开?