Cart.PHP
<div class="shopping-cart">
<section class="container content-section">
<h1>CART</h1>
<?php
$total = 0;
if (isset($_SESSION['cart'])){
$product_id = array_column($_SESSION['cart'], 'product_id');
$result = $db->getData();
while ($row = mysqli_fetch_assoc($result)){
foreach ($product_id as $id){
if ($row['id'] == $id){
cartElement($row['product_image'], $row['product_name'],$row['product_price'], $row['id']);
$total = $total + (int)$row['product_price'];
}
}
}
}else{
echo "<h5>Cart is Empty</h5>";
}
?>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">$0</span>
</div>
<button class="btn btn-primary btn-purchase" type="button">CONFIRM ORDER</button>
</section>
</div>
component.php
function cartElement($productimg, $productname, $productprice, $productid){
$element = "
<form action=\"cart.php?action=remove&id=$productid\" method=\"post\" class=\"cart-items\">
<div class=\"cart-row\">
<span class=\"cart-item cart-header cart-column\">$productname</span>
<span class=\"cart-price cart-header cart-column\">RM$productprice</span>
<span class=\"cart-quantity cart-header cart-column\"><input type=\"number\" value=\"1\" min=\"1\"></span>
<button type=\"submit\" class=\"btn btn-danger mx-2\" name=\"remove\">Remove</button>
</div>
<div class=\"cart-items\">
</div>
</form>
";
echo $element;
}
Hello everyone, I would like to count the quantity and the price of it which is the total. Is it possible to do with javascript or php and how? I have tried several ways to implement the function in javascript however none of my effort works.Thank you for helping me.
i don't know how the cart stores data on the session, but doing in the following way will make it easy.
$cartProducts = array_keys($_SESSION['cart']);
get product details from the DB something like:-
where product_id IN(implode(',',$cartProducts))"
loop through the products got from the DB
$total = 0;
while ($row = mysqli_fetch_assoc($result)){
$subtotal = $row['price'] * ($_SESSION['cart'][$row['id']]['quantity']);
$total += $subtotal;
// now you got product detail, quantity, price
// print the html formatted information here
}
at the end print the $total
if you change the quantity - then update the session cart, and repeat the above.
Note:- it is just an example, you need to add validations, fomat/secure sql etc