-1

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);
1
  • 2
    Don't do the concatenation in the query. Select the data you need so you can do direct calculations on it and only concatenate when you actually need to display it. Commented Feb 9, 2021 at 13:49

2 Answers 2

1

Avoid selecting data in a way that fits the purpose of displaying it. What you should do instead is grab only the data:

$select_stmt = $db->prepare("SELECT product, quantity, price FROM database");

Then you can easily do calculations with raw numbers:

while ($row = $select_stmt->fetch(PDO::FETCH_ASSOC))
{
    $items[] = $row["quantity"];
}
$sum = array_sum($items);

and have the display value created in PHP:

$displayItem = sprintf('%s (%d)', $row['product'], $row['quantity']);

If you insist, you could get that display string directly from the query, but then do it as an additional field:

$select_stmt = $db->prepare("SELECT product, quantity, price, CONCAT(product, ' (', quantity,')') AS ItemQty FROM database");

This way you still have quantity as a number to do calculations with and ItemQty to use for displaying purposes.

Sign up to request clarification or add additional context in comments.

Comments

-1

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);
?>

3 Comments

When writing an answer, you should include an explanation of why they should to it like this, like what you've changed and why.
Won't work. ItemQty is a string such as t-shirt(1), not an integer.
@El_Vanja i edit my answer, with regex i export number and push it to array and then sum all numbers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.