我有这个表单,我有一个选择列表和两个textboxex,可以动态添加以形成多行。场景是我将有一个选择值和多个文本框值。我想保存这是mysql表,它有三列:SelectValue,TextBox1Value和TextBox2Value。 SelectValue将相同/重复,但文本框值应该是唯一的。 我试过跟随php:
include('connection.php');
if(isset($_POST['submit'])){
$roomId = $_POST['roomno'];
$rowData = array();
foreach($_POST['inventoryname'] as $row=>$inventory){
$inventoryName = mysql_real_escape_string($inventory);
$inventoryCount = mysql_real_escape_string($_POST['inventorycount'][$row]);
$rowData[] = "('$inventoryName','$inventoryCount')";
}
}
if(!empty($rowData)){
$insert = mysql_query("INSERT INTO room_inventory_details(RoomId,Inventory,Count) VALUES('$roomId')".implode(',',$rowData));
if(!$insert){
die('Error: ' . mysql_error());
}else{
echo "Data saved successfullt";
}
}
这是我的标记
<form action="save_room_inventory.php" method="post" name="reservation-form" id="reservation_form">
<div class="left-form">
<label for="roomno"><span>Room No.</span>
<select name="roomno">
<option value="">---Please Select---</option>
<?php
include('connection.php');
$select_query = mysql_query("SELECT RoomId,RoomName FROM room ORDER BY RoomName");
while($rows = mysql_fetch_assoc($select_query)){ ?>
<option value="<?php echo $rows['RoomId']; ?>"><?php echo $rows['RoomName']?></option>
<?php }
?>
</select>
</label>
</div>
<div class="left-form">
<input type="button" id="addinventory" Value="Add Inventory">
</div>
<div class="inventory-table">
<div class="detail-table">
<table class="itemTable" border="1">
<thead>
<th>Inventory</th>
<th>Count</th>
<th><input type="button" value="Add New Row" id="addNew"></th>
</thead>
<tbody>
<tr class="cloneme">
<td>
<input type="text" name="inventoryname[]">
</td>
<td>
<input type="text" name="inventorycount[]">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="event_button">
<input type="submit" name="submit" value="Save">
<input type="reset" name="reset" Value="Clear">
<iframe name="acknowledgement" id="res_frame"></iframe>
</div>
</form>
保存时出现以下错误: 错误:SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在&#39;(&#39; Bed&#39;,&#39; 1&#39;)附近使用正确的语法,(&#39; Cderf&#39; &#39; 4&#39;)&#39;在第1行
答案 0 :(得分:0)
VALUES ('$roomId')
只有一个值,$rowData
每个只有两个值。你需要3个值。通过将$roomId
放入foreach
循环中的每个元素来实现这一点:
foreach($_POST['inventoryname'] as $row=>$inventory){
$inventoryName = mysql_real_escape_string($inventory);
$inventoryCount = mysql_real_escape_string($_POST['inventorycount'][$row]);
$rowData[] = "('$roomId', '$inventoryName','$inventoryCount')";
}
然后你的INSERT
应该是:
$insert = mysql_query("INSERT INTO room_inventory_details(RoomId,Inventory,Count) VALUES ".implode(',',$rowData));
顺便说一下,在分配mysql_real_escape_string
时也应该使用$roomId
。