简体   繁体   中英

PHP summing values from database - multidimensional arrays

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;
}

You are restarting the value $amount to 0 per iteration.

Try initializating it at the top:

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;
}

Just take out $amount = 0 out of the loop. As it's getting reset on each product loop.

$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'];
    }
} 

As I mentioned in my comment: In case you are able to change the way your shopping cart stores items, you could refactor your code to something like this:

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;
}

If would assume, that your shopping cart variable would contain something like this:

array(
   4 => 1,   // 1 item with ID 4
   22 => 8   // 8 items with ID 22
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM