我有下表从数据库中获取数据:
while($row = mysql_fetch_array($result))
{
echo '
<tr>
<td width="320">
<input type="checkbox" name="product_ID[]" value="'.$row['Product_ID'].'" />'.$row['Product_description'].'<br />
</td>
<td width="50">
<input type="text" name="product_cost[]" value="'.$row['Product_Retail_cost'].'" maxlength="3" size="3" />
</td>
<td width="50">
<input type="text" name="product_quantity[]" value="1" maxlength="3" size="1" />
</td>
</tr>';
}
我想做的是将行插入到表中,确保从两个文本框中插入任何更新的值。插入内容如下所示:
$product_ID = $_POST['product_ID'];
$product_cost = $_POST['product_cost'];
$product_quantity = $_POST['product_quantity'];
for ($i=0; $i<sizeof($product_ID);$i++)
{
$query="INSERT INTO mjj_ordered_products
(`Order_ID`,
`Product_ID`,
`Product_Quantity`,
`Product_Price`)
VALUES ((SELECT MAX(Order_ID) AS Order_ID FROM `mjj_orders`),
'".$product_ID[$i]."',
'".$product_quantity[$i]."',
'".$product_cost[$i]."')";
mysql_query($query) or die (mysql_error());
}
但是虽然这会插入正确的 Product_ID,但插入的其余两个值并不对应于选定的复选框,而是循环遍历整个列表。
问题:如何将与复选框关联的其他 2 个值插入到数据库中?
最佳答案
假设 Product_ID 是唯一的,您可以将其作为所有数组中的索引传递
<input type="text" name="product_cost['.$row['Product_ID'].']" value="'.$row['Product_Retail_cost'].'" maxlength="3" size="3" />
然后做类似的事情
foreach($product_ID as $id)
{
$query="INSERT INTO mjj_ordered_products
(`Order_ID`,
`Product_ID`,
`Product_Quantity`,
`Product_Price`)
VALUES ((SELECT MAX(Order_ID) AS Order_ID FROM `mjj_orders`),
'".$product_ID[$id]."',
'".$product_quantity[$id]."',
'".$product_cost[$id]."')";
mysql_query($query) or die (mysql_error());
}
关于php - 根据选中的复选框将所有值插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12146820/