2
我正在尋找使用一個pdo語句的輸出與另一個語句的數組數據。目前,這兩組語句都單獨工作,但我不知道如何將輸出合併到數據庫中的一個表中。如何將兩個用於INSERT的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));
}
?>
沒有必要在這種情況下更多的使用'mysql_escape_string'(實際上,這是錯誤的,可能會打破字符串)。 PDO在準備好的聲明中執行轉義工作 – 2012-03-11 23:49:38
@Pekka感謝您的更新,我將更新我的代碼,仍然掌握PDO。如果你對如何獲得輸出結果有任何想法,我會非常感激。 – 2012-03-11 23:54:03
當前代碼有什麼問題? – galymzhan 2012-03-12 05:11:05