Count quantity shopping cart

Asked

Viewed 131 times

2

Good evening, I need to count the amount of products that are in the cart in the quantity field.

I am using PHP PDO and MYSQL

TABLE

id | quantidade | produto
 1 |     5      |   582
 2 |     8      |   122

The total needs to give 13, in this code below it gives 2

CODE

$stmtCount = $pdo->prepare("SELECT COUNT(quantidade) as total FROM carrinho");
$stmtCount->execute();
$resultCount = $stmtCount->fetch(PDO::FETCH_OBJ);

HTML

<div class="cart-det">
    <?php if(empty($resultCount->total)):?>
        <span class="cart-count">0</span>
    <?php else: ?>
        <span class="cart-count"><?php echo $resultCount->total; ?></span>
    <?php endif; ?>
    <ion-icon name="cart"></ion-icon>
</div>

1 answer

3


The COUNT returns only the number of rows that meet the search criteria. What you need to use to add up the values of a column is the SUM.

Your code would then look like this:

$stmtCount = $pdo->prepare("SELECT SUM(quantidade) as total FROM carrinho");
$stmtCount->execute();
$resultCount = $stmtCount->fetch(PDO::FETCH_OBJ);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.