suppose, I have saved all the product codes in the table named as code_table
, I am here not representing that table.
I am trying to get sum()
of the LAST INSERT rate
column rows.
in the below code I have used, but I couldn't get the output as expected.
Please help me how I get the all product SKU rate under foreach loop.
I have read all the threads but it all was not helpful for me.
TABLE = test
ID | product_sku | rate | code
-------------------------------
1 | 1230 | 23 | 111
-------------------------------
2 | 1230 | 25 | 111 //COUNT THIS ROW ONLY
-------------------------------
3 | 1231 | 20 | 222
-------------------------------
4 | 1231 | 26 | 222 //COUNT THIS ROW ONLY
Total SUM WILL BE = 51 // ROW ID 2 + 4 AS 25 + 26 = 51
$sql = $con->prepare("SELECT * FROM `code_table`");
$sql->execute();
foreach ($result as $data => $value) {
$stmt = $con->prepare("SELECT *, SUM(`rate`) AS `totalCost`
FROM `test`
WHERE `code` = :code");
$stmt->execute(array(':code' => $value['product_code']));
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
$sum = 0;
$sum+= $data['totalCost']
}
}
echo $sum; //expected result = 51