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

时间:2022-09-26 08:17:25

Can someone please explain to me how I can import the array data I am outputting into rows on my database.

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

HTML

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>

This is passed to a php form:

这传递给php表单:

foreach($_POST['recipe'] as $key=>$value)
    {   

    }

print_r($_POST);

and outputs the following array:

并输出以下数组:

Array ( 
    [recipe] => Array ( 
        [ingredient] => Array ( 
            [1] => eggs 
            [2] => milk 
            [3] => flour
        ) [quantity] => Array ( 
            [1] => 12 
            [2] => 13 
            [3] => 14 
        ) 
    ) 
)

I need to import each of the individual ingredients and quantities to a new row in my database table. I am using PDO to connect to my database but I am unsure how I can insert the data from the array into the rows on my database.

我需要将每个单独的成分和数量导入我的数据库表中的新行。我正在使用PDO连接到我的数据库,但我不确定如何将数组中的数据插入到我的数据库中的行中。

Thanks.

谢谢。

3 个解决方案

#1


2  

Well i would stucture my form a bit differently so you get ingerdients assemebled as their own array, but with the stcuture you have:

好吧,我会把我的形式结构有点不同,所以你得到ingerdients作为他们自己的数组,但你有stcuture:

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

#2


1  

Simple example without error checking:

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

<?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]
        ));
    }

?>

Note that normally you should start counting indexes from 0 and if you just write recipe[ingredient][] PHP will automatically create the indexes.

请注意,通常您应该从0开始计算索引,如果您只是编写recipe [ingredient] [],PHP将自动创建索引。

#3


0  

I assume your problem is the format of the $_POST array. You have:

我假设您的问题是$ _POST数组的格式。你有:

[recipe][ingredient][...] and
[recipe][quantity][...]

However that's not the structure of your database which organized it in rows and columns:

但是,这不是数据库的结构,它按行和列组织它:

[recipe][...][ingredient, quantity]

You can see how the [...] moves around. You need to map the array format to your database format. This is easiest done with a foreach:

你可以看到[...]如何移动。您需要将数组格式映射到数据库格式。这是最简单的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];
}

After you've run this, use print_r to verify everything went right:

运行之后,使用print_r验证一切正常:

print_r($recipes);

You can now use the $recipes array to insert your data into the database for each row (I assume you know how you do the insert SQL query so I don't put it into the answer).

您现在可以使用$ recipes数组将数据插入到每行的数据库中(我假设您知道如何执行插入SQL查询,因此我不会将其放入答案中)。

#1


2  

Well i would stucture my form a bit differently so you get ingerdients assemebled as their own array, but with the stcuture you have:

好吧,我会把我的形式结构有点不同,所以你得到ingerdients作为他们自己的数组,但你有stcuture:

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

#2


1  

Simple example without error checking:

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

<?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]
        ));
    }

?>

Note that normally you should start counting indexes from 0 and if you just write recipe[ingredient][] PHP will automatically create the indexes.

请注意,通常您应该从0开始计算索引,如果您只是编写recipe [ingredient] [],PHP将自动创建索引。

#3


0  

I assume your problem is the format of the $_POST array. You have:

我假设您的问题是$ _POST数组的格式。你有:

[recipe][ingredient][...] and
[recipe][quantity][...]

However that's not the structure of your database which organized it in rows and columns:

但是,这不是数据库的结构,它按行和列组织它:

[recipe][...][ingredient, quantity]

You can see how the [...] moves around. You need to map the array format to your database format. This is easiest done with a foreach:

你可以看到[...]如何移动。您需要将数组格式映射到数据库格式。这是最简单的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];
}

After you've run this, use print_r to verify everything went right:

运行之后,使用print_r验证一切正常:

print_r($recipes);

You can now use the $recipes array to insert your data into the database for each row (I assume you know how you do the insert SQL query so I don't put it into the answer).

您现在可以使用$ recipes数组将数据插入到每行的数据库中(我假设您知道如何执行插入SQL查询,因此我不会将其放入答案中)。