如何通过foreach循环发送多个字段值?

时间:2013-02-28 12:33:42

标签: php html

如何使用相同的ID通过foreach循环发送多个字段值?

这个HTML代码有什么问题?

<input type="text" size="3" name="new_quantity[<?php echo $product_id; ?>]" value="<?php echo $product_quantity; ?>" />
<input type="text" name="totalcost[<?php echo $product_id; ?>]" value="<?php $total_cost; ?>"  />

现在是PHP代码

foreach($_REQUEST['new_quantity'] as  $key => $quantity) {
    foreach($_REQUEST['totalcost'] as $key => $total) {
        $sql=mysql_query("UPDATE `categories`.`carts` SET `product_quantity` = '$quantity',                `product_totalcost` = '$total' WHERE `carts`.`product_id` ='$key' AND  cart_session='$sessionID'");
    }
}

2 个答案:

答案 0 :(得分:0)

循环内的循环将为您提供n * n次更新查询

但实际上你需要n次更新查询

所以这样做:

$pids     = array_keys($_REQUEST['new_quantity']); /// here you will get all product_ids

for($i=0; $i<count($_REQUEST['new_quantity']);$i++){
   echo $_REQUEST['new_quantity'][$pids[$i]]; // this quantity
   echo $_REQUEST['totalcost'][$pids[$i]]; // total cost
   echo $pids[$i]; // product id

   /// add your update query here all details you need in query are echoed above.
}

答案 1 :(得分:-1)

尝试为数量制作一个数组,为费用

创建一个数组

$qt=array();
foreach($_REQUEST['new_quantity'] as  $key => $quantity) {
$qt[].=$quantity;
}

$ct=array();
foreach($_REQUEST['totalcost'] as $key => $total) {
$ct[].=$total;
}

然后在for循环中触发更新查询