如何将INSERT的两个PDO语句组合到数据库中?

时间:2012-03-11 23:28:24

标签: php database arrays pdo

我希望将一个pdo语句的输出与另一个语句的数组数据一起使用。目前这两组语句都可以单独运行,但我不知道如何将输出合并到我的数据库中的一个表中。

我要更新的数据库表有3列,recipe_iditem_numberquantity

我需要的是$recipeID用作主recipe_id以及我的数组的输出来填充其他两列。希望我有意义并且有人可以提供帮助,我正在使用的代码如下所示:

<?php
        //MySQL Database Connect
        require 'config.php';

        //Takes form input for recipe title for insert to the recipe table
        $name = $_POST["recipeName"];

        //Stored procedure inputs the recipe name to the recipe table and outputs a recipe_id which is to be passed into recipe item table below
        $stmt = $dbh->prepare( "CALL sp_add_recipe(:name, @output)" );
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);

        //Execute Statment
        $stmt->execute();

        //$recipeID variable stores recipe_id outputted from the stored procedure above
        $recipeID = $dbh->query( "SELECT @output" )->fetchColumn(); 

        //Insert places the values from $recipeID, item_number & quantity into the recipe_item table
        $stmt = $dbh->prepare('INSERT INTO recipe_item (recipe_id, item_number, quantity) VALUES (:recipeID,?,?)');
        $stmt ->bindParam(':recipeID',$recipeID, PDO::PARAM_STR);

        //Ingredients variable combines array values from HTML form
        $ingredients = array_combine($_POST['recipe']['ingredient'], $_POST['recipe']['quantity']);

        //Each value from the form is inserted to the recipe_item table as defined above
        foreach($ingredients as $name => $quantity)
        {
            $stmt->execute(); //I would like to insert $recipeID to my database with each line of the array below.
            $stmt->execute(array($name, $quantity)); 
        }
    ?>

1 个答案:

答案 0 :(得分:2)

$stmt = $dbh->prepare('INSERT INTO recipe_item (recipe_id, item_number, quantity) VALUES (:recipeID,:number,:quantity)');

//remove the bindParam() call for recipeId

$ingredients = array_combine($_POST['recipe']['ingredient'], $_POST['recipe']['quantity']);

foreach ($ingredients as $name => $quantity) {
    $bound = array(
        'recipeID' => $recipeID,
        'number' => $name, // ?? This is what your codes does at the moment, but looks weird
        'quantity' => $quantity
    );
    $stmt->execute($bound);
}