我正在为我的网站制作购物车。在购物车区域,我从数据库中提取运输详细信息,包括取决于邮政编码的价格。当用户点击“更新购物车”时。我正在尝试使用运费更新总数。如果有人能指出我解决这个问题的正确方向。
这是我显示购物车的功能。
function showCart() {
$cart = $_SESSION['cart'];
$zip = $_SESSION['zipcode'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE id = '.$id;
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
extract($row);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
$output[] = '<td>'.$title.' by '.$author.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$sql = 'SELECT * FROM zipcodes WHERE zipcode = '.$zip;
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$output[] = '<label>Price: </label><select name="delivery" id="delivery" class="long-field">';
$output[] = '<option value="">Please Select</option>';
$output[] = '<option value='.$row['free_dev'].'>$'.$row['free_dev'].'</option>';
$output[] = '<option value='.$row['next_day_dev'].'>$'.$row['next_day_dev'].'</option>';
$output[] = '</select>';
}
$output[] = '<p>Delivery Charge: <strong>$'.$delivery.'</strong></p>';
$output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>';
$output[] = '<div><button type="submit">Update cart</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
}
return join('',$output);
}
这是通过 cart.php 更新的部分
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
if (stristr($key,'qty')) {
$id = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
for ($i=1;$i<=$value;$i++) {
if ($newcart != '') {
$newcart .= ','.$id;
} else {
$newcart = $id;
}
}
}
}
}
$cart = $newcart;
break;
谢谢你。任何帮助是极大的赞赏!PS我正在使用这里的购物车教程http://v3.thewatchmakerproject.com/journal/276/