1

My table value is:

id stock
1   7|8
2   80|50|30

and my query is

I used PHP function

function numofQuantity() {

    $sql = "SELECT sum(stock) as quantity FROM products";
    $result = dbQuery($sql);
    $data=mysql_fetch_assoc($result);
    return $data['quantity'];

}

Here it shows the result is 87.

How to sum all the values? Thank you

1
  • 3
    Instead of fixing this, you should rather normalize your database so you can actually run SUM(stock) on there. You should have one column for ID, and one for each stock. Commented Nov 29, 2013 at 9:44

3 Answers 3

4

Never store multiple values in one column!

As you see now that will only lead to problems. You should rather change your DB design. Use another table to store the stock:

stock table
-----------
id
product_id
stock

The you could sum the stock like this

SELECT p.id, sum(s.stock) as quantity 
FROM products p
inner join stock s on s.product_id = p.id
group by p.id
Sign up to request clarification or add additional context in comments.

Comments

2

Now it is difficult to do in Mysql. You can do it php like below:

function numofQuantity() {

    $sql = "SELECT stock FROM products";
    $result = dbQuery($sql);
    $data=mysql_fetch_assoc($result);
    $arrayVal = explode("|", $data['stock']);
    return array_sum($arrayVal)

}

For more info :https://www.php.net/array_sum

Comments

1

First of all, you should normalize your database if you wish to do anything with the individual values inside a column.

Without normalization you will need the support of PHP (PDO example):

$sum = 0;
$res = $db->query('SELECT stock FROM products');
foreach ($res->fetchAll(PDO::FETCH_COLUMN) as $stocks) {
    $sum += array_sum(explode('|', $stocks));
}

echo $sum;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.