我在嘗試用新條目更新菜餚表並將其交叉引用到現有的配料表中。對於添加的每道菜,用戶都需要分配現有配料和多條生產線所需的體積。提交時,應將盤子輸入「盤子」表格中,並將所分配的成分輸入到「DishIng」鏈接表格中。從PHP插入多個MySQL的問題
我的表是這樣設置:
Table: "Dishes" Columns: DishID, DishName, Serves, etc...
Table: "DishIng" Columns: DishID, IngID, Volume
Table: "Ingredients" Columns: IngID, IngName, Packsize etc...
HTML:
<form action="Array.php" method="post">
<ul>
<li>DishID: <input type="text" name="DishID"></li>
<li>Name: <input type="text" name="DishName"></li>
<li>Catagory : <input type="text" name="DishCatID"></li>
<li>Serving: <input type="text" name="Serving"></li>
<li>SRP: <input type="text" name="SRP"></li>
<li>Method : <input type="text" name="Method"></li>
<li>Source : <input type="text" name="SourceID"></li>
<br>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
</ul>
<input type="submit">
</form>
動態地添加在HTML成分的排任何建議將是非常歡迎的。
PHP:
<?php
require_once('db_connect.php');
$DishID = mysqli_real_escape_string($con, $_POST['DishID']);
$DishName = mysqli_real_escape_string($con, $_POST['DishName']);
$DishCatID = mysqli_real_escape_string($con, $_POST['DishCatID']);
$Serving = mysqli_real_escape_string($con, $_POST['Serving']);
$SRP = mysqli_real_escape_string($con, $_POST['SRP']);
$Method = mysqli_real_escape_string($con, $_POST['Method']);
$SourceID = mysqli_real_escape_string($con, $_POST['SourceID']);
$IngID = mysqli_real_escape_string($con, $_POST['IngID']);
$Volume = mysqli_real_escape_string($con, $_POST['Volume']);
$array = array('$DishID', '$IngID', '$Volume');
$sql="INSERT INTO Dishes (DishID, DishName, DishCatID, Serving, SRP, Method, SourceID)
VALUES ('$DishID', '$DishName', '$DishCatID', '$Serving', '$SRP', '$Method', '$SourceID')";
$sql2 = "INSERT INTO DishIng (DishID, IngID, Volume) VALUES ('$DishID', '$IngID', '$Volume')";
$it = new ArrayIterator ($array);
$cit = new CachingIterator ($it);
foreach ($cit as $value)
{
$sql2 .= "('".$cit->key()."','" .$cit->current()."')";
if($cit->hasNext())
{
$sql2 .= ",";
}
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con));
}
echo "records added";
require_once('db_disconnect.php');
php?>
目前上提交,它僅更新「菜」表,並給了我這個消息:「1個紀錄addedError:您在您的SQL語法錯誤; ('0','$ DishID'),('1','$ IngID'),('2','$ Volume')附近使用正確的語法檢查與您的MySQL服務器版本相對應的手冊。 'at line 1'
變量不會在單引號內部擴展。所以'$ array'包含字符串'$ DishID',而不是該變量的值。你爲什麼要把這些值放在引號中? – Barmar 2014-09-23 07:49:35
您的表單中有多個字段具有相同的名稱。只有其中一個將被提交。你應該給他們以'[]'結尾的名字,然後PHP將它們收集到一個數組中。 – Barmar 2014-09-23 07:51:09
我真的很努力做到這一點,正確的是我的foreach語句的基礎,正如其他人正在採取的那樣,而不是數組元素。你會如何建議這是最好的書面? – nbren007 2014-09-23 11:15:47