【发布时间】:2015-11-15 19:52:51
【问题描述】:
我有一个包含 2 个动态字段的 HTML 表单:
<input type="text" name="ingredients[]" placeholder="Ingredients"/></div>
<input type="text" name="quantity[]" placeholder="Quantity"/></div>
看这里,对于表单中的那些输入,db 表应该是这样的 英格 1 1001 1KG 英格 2 1001 2KG 3 1001 3KG
现在检查图像,你会看到发生了什么
我的 php 文件中有配方 ID,我只想要一个 PDO 代码来帮助我连续插入“成分”、“数量”和“$recipe_ID”。
<?php
header('Content-type: application/json');
require_once 'db/pdoconnect.php';
if($_POST)
{
$sth = $con->prepare("SELECT `recipeid` FROM Recipes ORDER BY `recipeid` DESC");
$sth->execute();
$previousid = $sth->fetchColumn();
$offset=1;
$generatingid=$previousid+$offset;
$newid=$generatingid;
//print("Last Id=$previousid\n");
//print("New Id=$newid\n");
$title = $_POST['title'];
$preptime = $_POST['preptime'];
$cocktime = $_POST['cocktime'];
$level = $_POST['level'];
$serving = $_POST['serving'];
$recipetype = $_POST['recipetype'];
$intro = $_POST['intro'];
$details = $_POST['details'];
$image = $_POST['image'];
try
{
$stmt = $con->prepare("INSERT INTO Recipes (recipeid,title,preptime,cocktime,level,serving,recipetype,intro,details,recipeimg) VALUES( :newid, :title, :preptime, :cocktime, :level, :serving, :recipetype, :intro, :details, :image)");
$stmt->bindParam(":newid",$newid);
$stmt->bindParam(":title",$title);
$stmt->bindParam(":preptime",$preptime);
$stmt->bindParam(":cocktime",$cocktime);
$stmt->bindParam(":level",$level);
$stmt->bindParam(":serving",$serving);
$stmt->bindParam(":recipetype",$recipetype);
$stmt->bindParam(":intro",$intro);
$stmt->bindParam(":details",$details);
$stmt->bindParam(":image",$image);
if($stmt->execute()) { //check if main query has been executed
$sql = "INSERT INTO Ingredients VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:recipeid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':recipeid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
if ($sth->execute()) {
$response_array['status'] = 'success';
}
}//END OF FIRST IF STATEMENT
else{
$response_array['status'] = 'error';
}
echo json_encode($response_array); //SEND THE RESPONSE
}//END OF TRY
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
【问题讨论】:
-
很好,你有问题吗?
-
我需要知道怎么做?
-
您正在使用或尝试插入的查询。