【发布时间】:2012-03-28 10:23:34
【问题描述】:
我希望将一个 pdo 语句的输出与另一个语句的数组数据一起使用。目前,两组语句都可以单独工作,但我不知道如何将输出合并到我的数据库中的一个表中。
我要更新的数据库表有 3 列,recipe_id、item_number 和 quantity。
我需要将 $recipeID 用作主要的 recipe_id 并将我的数组的输出用于填充其他两列。希望我说得通,有人可以提供帮助,我正在使用的代码如下所示,带有 cmets:
<?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));
}
?>
【问题讨论】:
-
这种场景下不用
mysql_escape_string了(其实是错误的,可能会断字符串)。 PDO 在准备好的语句中进行转义 -
@Pekka 感谢您的更新,我将更新我的代码,但仍要掌握 PDO。如果您对我如何获得输出有任何想法,我将不胜感激。
-
当前代码有什么问题?
-
嗨@galymzhan 目前第一条语句正确地将配方名称插入到我的主配方表并将id输出到$recipeID但是当我尝试将它包含在foreach循环中时数组什么都没有发生。如果我排除 $recipeID 并仅使用数组自行执行 foreach 循环,则数据库中的 $name 和 $quantity 会正确更新,但它缺少 $recipeID(或者它只是将其插入为 0)。任何想法都会很棒......