Reputation: 115
I am looking to use the output from one pdo statement with the array data of another statement. At the moment both set of statements work fine individually but I don't know how I can go about merging the outputs into one table on my database.
The database table I am trying to update has 3 columns, recipe_id
, item_number
and quantity
.
What I need is for $recipeID
to be used as the main recipe_id
and the outputs from my array to fill the other two columns. Hopefully I am making sense and someone can help, the code I am using is shown below with comments:
<?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));
}
?>
Upvotes: 2
Views: 503
Reputation: 29411
$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);
}
Upvotes: 2