0

I have a problem with sum values in while loop. So, I have a database witch has rows with same product name, but different quantities, different ids and different prices. When I do my while loop it prints each product, but I want to print only one and sum quantities.

My result is 11123, not 8, how it should be.

This is my code:

$found = 1;
while($stmt->fetch()){
    if(!($data3['Prod_price'] == '0' || $data3['Prod_name'] == ' Acne Cream')) {
        $price = $data3['Prod_total'] - ($data3['Prod_total'] *($data3['Discount']/100));
        $qty = $data3['Vial_type'] == " 50 Tablete" ? $data3['Prod_qty'] / 2 : $data3['Prod_qty'];
        if($data3['Prod_name'] == ' Antioxidant Star'){
            if($found==1){ // this is for showing only one product with same name 
                $found++;

                // here should be summed quantity divided by target (to extract the percentage)
                $andioxidtrg = $qty / $data2['Trg_antioxidant']; 
                // here shold be the quantity
                $andioxidqty = $qty; 

                echo 'Antioxidant Star: '.$andioxidqty.' din '.$data2['Trg_antioxidant'].' ('.round( $andioxidtrg * 100 )."%)<br>";
            }
        }
    }
}
0

1 Answer 1

1

If you want to sum then sum it, you just overwrite the value.

$andioxidqty += $qty; // notice the +

Edit: this means you also need to add a line above the loop with: $andioxidqty =0; or you will get a notice on the first iteration

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

10 Comments

How can it be 1 if you say it's 11123? On the first iteration, yes it's one but when the loop is done you should have 8 as the value in $andioxidqty
if i echo the "$qty" above the "if($found==1){" line the result is "11123" but inside the if statement "if($found==1)" the result is always 1 :(
if($found==1){ is true the first iteration, then the very next line makes this if never again be true, $found++;. What is this found thing? It does not make any sense
You are checking found to be equal to 1. then increment it to 1 so result will be incremented only once
@ZiyaVakhobov I can't accept that edit, it's wrong. PHP typecasts if you add int to a string number. 3v4l.org/U6Jep
|

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.