Mourad karoudi Mourad karoudi - 4 months ago 20
MySQL Question

Count total price of items with php

I Create a simple php shopping cart :


  • Add product with quantity.

  • update quantity of product.



I want to count total price of all items in cart but I don't know how ?

I display items with this code :

<?php
session_start();
$where = implode(",",$_SESSION['product']);
$get_p = $mysqli->prepare("select id,name,price,imgs,quantity from products where id IN ($where)");
$get_p->execute();
$get_p->bind_result($id,$name,$price,$imgs,$quantity);
$get_p->store_result();
while($get_p->fetch()) {
$qty = $_SESSION["qty"][$id];
$total = $qty * $price;
?>
<tr>
<td><img src="<?php echo htmlspecialchars($imgs); ?>"/></td>
<td><?php echo htmlspecialchars($name); ?></td>
<td><?php echo htmlspecialchars($price)."×".$qty; ?></td>
<td><input type="number" value="<?php echo $qty; ?>" min="1" name="qty_cart"></td>
<td><input type="submit" value="delete" name="delete<?php echo $id; ?>"/></td>
<?php
if(isset($_POST["delete".$id])) {
unset($_SESSION['product'][$id]);
}
?>
</tr>
<?php
}

?>
</table>
<div class="price_all_items">
</div>
<input type="submit" name="sub" value=""/>
</form>

Answer

Replace this part of your code

while($get_p->fetch()) {
    $qty = $_SESSION["qty"][$id];
    $total = $qty * $price;

with this

$totalSum = 0;
while($get_p->fetch()) {
    $qty = $_SESSION["qty"][$id];
    $total = $qty * $price;
    $totalSum += $total;

and after you end of your loop the value in $total will have total amount.