0

I need to calculate a sub total of the items in a shopping cart. It stores the items added to the cart as an array of the product IDs in a session variable.

So to start with I need to use the ID in the cart array to pull the product information from the database (name, price etc.) and then add the prices of all the items in the cart, of which there could be more than one of the same product.

My test cart should have a total price of 96,049.98 but my code is returning a total price of 18. I don't know where it's getting that from.

Here is the code:

function subTotal() {
global $db;
global $table_prefix;
$table = $table_prefix . "products";

foreach($_SESSION['cart'] as $item) {
    $sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
    $sql->bindParam(":id", $item[0]);
    $sql->execute();

    $amount = 0;
    $product = $sql->fetch(PDO::FETCH_ASSOC);
    foreach($product as $price) {
        $amount += $price['price'];
    }
}   
return $amount;
}
4

3 回答 3

2

您正在将$amount每次迭代的值重新设置为 0。

尝试在顶部初始化它:

function subTotal() {
global $db;
global $table_prefix;
$table = $table_prefix . "products";
$amount = 0;  //MOVED HERE at the top

foreach($_SESSION['cart'] as $item) {
    $sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
    $sql->bindParam(":id", $item[0]);
    $sql->execute();

    $product = $sql->fetch(PDO::FETCH_ASSOC);
    foreach($product as $price) {
        $amount += $price['price'];
    }
}   
return $amount;
}
于 2013-05-03T13:23:55.833 回答
1

正如我在评论中提到的:如果您能够更改购物车存储商品的方式,您可以将代码重构为如下所示:

function subTotal() {
    $db = $GLOBALS['db'];
    $table_prefix = $GLOBALS['table_prefix'];

    $table = $table_prefix . "products";
    $totalPrice = 0;

    // assuming that you actually store ($id => $amount) pairs
    $ids = join(',', array_map('intval', array_keys($_SESSION['cart'])));

    $stmt = $db->prepare("SELECT id, price FROM $table WHERE id IN ($ids)");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
       $amount = $_SESSION['cart'][$row['id']];
       $totalPrice += $amount * $row['price'];
    }

    return $totalPrice;
}

如果假设,您的购物车变量将包含如下内容:

array(
   4 => 1,   // 1 item with ID 4
   22 => 8   // 8 items with ID 22
)
于 2013-05-03T13:37:21.010 回答
1

只是从$amount = 0循环中取出。因为它在每个产品循环上都被重置。

$amount = 0;
foreach($_SESSION['cart'] as $item) {
    $sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
    $sql->bindParam(":id", $item[0]);
    $sql->execute();    
    $product = $sql->fetch(PDO::FETCH_ASSOC);
    foreach($product as $price) {
        $amount += $price['price'];
    }
} 
于 2013-05-03T13:23:43.483 回答