我正在构建一个PHP购物车,从mySQL数据库中提取商品信息和价格。这实际上是完美的运作。问题是我现在需要添加使用表单数据而不是数据库将项目添加到购物车的功能。我需要这样做的原因是它是一个有多种选择的构建你自己的东西。所以我用单选按钮创建了一个表单。我已成功完成从数据库添加项目以及添加表单提供购买的多个版本。我唯一的问题是总价。我总得到奇怪的结果。如果我从数据库添加多个项目,则总计算完美。如果我从表单中添加多个项目,则总计算完美。如果我混合两者,就会发生奇怪的事情。我只用PHP编写了5个月左右,所以还是很新的。在没有运气的情况下反复搜索论坛和YouTube。有什么想法吗?
function cart() {
//Here is where items are added from the MySQL db.
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '<p>'.$get_row['name'].' x '.$value.' @ $'.number_format($get_row['price'], 2).' = $'.number_format($sub, 2).' <a href="cart-BE.php?remove='.$id.'">[-]</a> <a href="cart-BE.php?add='.$id.'">[+]</a> <a href="cart-BE.php?delete='.$id.'">[Delete]</a></p>';
}
}
//Here is where the total is calculated from the db items.
$total += $sub;
}
}
//Here is where I add item from user form input.
if (!empty($_SESSION['box_id_array'])) {
foreach($_SESSION['box_id_array'] as $v1) {
echo $_SESSION['box_pops_cart_'.$v1]['CakeFlavors'].' <a href="testing.php?remove_box='.$v1.'">Remove</a><br />';
//Here is where I attempt to add the form total to db total. I assume the problem is here.
$total += $_SESSION['box_pops_cart_'.$v1]['box_price'];
}
}
if ($total==0) {
echo "Your cart is empty.";
} else {
echo '<p>Total: $'.number_format($total, 2).'</p>';
?>
<form action="checkouttest.php" method="post">
<?php submit_items(); ?>
<input type="submit" name="checkout" id="checkout_btn" value="Checkout" />
</form>
<?php
}
}