I am getting the price of the product from db using the product id i have stored in php array.
i have a php function where in i want to hold a total of all the products purchased. here i am getting the cart items and i am calling the function which should hold total amount. i am passing the value price
each time when i retrieve the product from cart.
for example for first item iteration i send value 300, and for second 400, for third 900.
i want to add up all these and get total price of 1600 in payableAmount()
how can i do this?
function getCartitems($product_id){ $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT product_id,product_name,product_price,product_image_url FROM product_list WHERE product_id='$product_id'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>₹ </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>"; $price = $row['product_price']; payableAmount($price); } } else { echo "There are no such items"; } $conn->close(); } function payableAmount($totalPrice){ // calculate total price here $total = $totalPrice; echo $total; }
Advertisement
Answer
You just simply update your query instead like as
$total_price = 0; while($row = $result->fetch_assoc()) { echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>₹ </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>"; $total_price += $row['product_price']; }