Search code examples
phpmysqlmeekro

Sum available quantities in stock with meekro library


Table: stock

╔═════════════╦═══════════════════╦══════════╦═══════════════╗
║ id          ║ product_id        ║ store_id ║ quantity      ║
╠═════════════╬═══════════════════╬══════════╬═══════════════╣
║  1          ║ 1                 ║   1      ║10             ║
║  2          ║ 1                 ║   2      ║20             ║
║  3          ║ 2                 ║   1      ║10             ║
║  4          ║ 2                 ║   2      ║20             ║
║  5          ║ 2                 ║   3      ║30             ║
║  6          ║ 3                 ║   1      ║10             ║
║  7          ║ 3                 ║   2      ║20             ║
╚═════════════╩═══════════════════╩══════════╩═══════════════╝

Currently this is my query:

<?php
$QueryStock = DB::query("SELECT * FROM stock WHERE product_id = 2");
foreach ($QueryStock as $Stock) {
    echo $Stock['quantity']."<br>";
}
?>

I get:

10
20
30

I am using the meekro library, I am trying to obtain the sum of the quantities of my products, do you have any idea how I should make the sum to get the total amount of all the stores?


Solution

  • You can sum all quantities and get the final result. In that case the foreach statement used after become useless:

    SELECT sum(quantity) as total FROM stock WHERE product_id = 2;