我希望将一个 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));
}
?>
最佳答案
$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);
}
关于php - 如何将两个 PDO 语句组合起来插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659962/