【问题标题】:Insert Array data into a database using PDO使用 PDO 将数组数据插入数据库
【发布时间】:2012-03-28 08:36:54
【问题描述】:

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

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 连接到我的数据库,但我不确定如何将数组中的数据插入到我的数据库中的行中。

谢谢。

【问题讨论】:

  • 重组你的数据库,并有一个单独的成分表...不要将它们全部存储在配方表的列中
  • @Mark Ba​​ker 感谢您的评论。我目前确实将我的数据库分为成分、食谱标题和食谱项目表。我需要从数组中获取数据并将其插入到配方项目表中,但我不确定如何使用 PDO 做到这一点。任何帮助将不胜感激。

标签: php html arrays forms pdo


【解决方案1】:

嗯,我会以不同的方式构造我的表单,这样你就可以将成分组装成他们自己的数组,但是使用你拥有的结构:

$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?
}

【讨论】:

  • 感谢大家@prodigitalson 的帖子,您上面的代码起到了作用。非常感谢!
【解决方案2】:

没有错误检查的简单示例:

<?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会自动创建索引。

【讨论】:

    【解决方案3】:

    我认为您的问题是$_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 查询,因此我不会将其放入答案中)。

    【讨论】:

      猜你喜欢
      • 2016-09-11
      • 2014-08-28
      • 2014-04-17
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2018-08-01
      • 2013-11-17
      相关资源
      最近更新 更多