Как объединить два оператора PDO для INSERT в базу данных? - PullRequest
2 голосов
/ 12 марта 2012

Я хочу использовать вывод одного оператора pdo с данными массива другого оператора.В настоящее время оба набора операторов работают отлично по отдельности, но я не знаю, как я могу объединить выходные данные в одну таблицу в моей базе данных.

Таблица базы данных, которую я пытаюсь обновить, имеет 3 столбца, recipe_id, item_number и quantity.

Мне нужно, чтобы $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 Ответ

2 голосов
/ 12 марта 2012
$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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...