Search code examples
phploopspdosum

Sum column values while looping over a query result set


The following script shows the product and the quantity. Par example: t-shirt(1), boxershort(2).

Now I would like to show the sum of all items, in this case "3".

How can I get an array_sum of this?

$allItems = "";
$items = array();
$select_stmt = $db->prepare("SELECT CONCAT(product, ' (', quantity,')') AS ItemQty, price 
FROM database");
$select_stmt->execute();
while ($row = $select_stmt->fetch(PDO::FETCH_ASSOC))
{
    $items[] = $row["ItemQty"];
}
$allItems = implode(", ", $items);

Solution

  • you should do this:

    <?php
    $allItems = "";
    $items = array();
    $select_stmt = $db->prepare("SELECT CONCAT(product, ' (', quantity,')') AS ItemQty, price 
    FROM database");
    $select_stmt->execute();
    while ($row = $select_stmt->fetch(PDO::FETCH_ASSOC))
    {
        preg_match('/[0-9]+/', $row["ItemQty"], $match);
        array_push($items, (int)$match);
    }
    echo array_sum($items);
    $allItems = implode(", ", $items);
    ?>