Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum count query inside foreach loop?

Tags:

php

mysqli

<?php 
    foreach($idd as $ids)
    {
        $sql5 = "select count(DISTINCT product_name) as total from stock where type = '".$ids."'";
        $result5 = mysqli_query($con,$sql5);
        $row5 = mysqli_fetch_row($result5);
    }
    $total5 = $row5[0];
?>

In this code I have used explode function for $idd and run query inside foreach loop and want to sum of multiple query inside foreach loop and Now, My query look like:

select count(DISTINCT product_name) as total from stock where type = 'Green Tea'select count(DISTINCT product_name) as total from stock where type = 'Herbal Tea'

But I want like this

select (select count(DISTINCT product_name) as total from inventory_add_in_stock where type = 'Green Tea')+(select count(DISTINCT product_name) as total from inventory_add_in_stock where type = 'Herbal Tea') as total

So, How can I do this? Please help me.

Thank You

like image 252
omkara Avatar asked Mar 06 '26 02:03

omkara


1 Answers

You need to fetch values inside foreach() and sum them. Do like below:-

<?php

    $total_count = 0; // a varible define to get total count in last
    foreach($idd as $ids)
    {
        $sql5 = "select count(DISTINCT product_name) as total from stock where type = '".$ids."'";
        $result5 = mysqli_query($con,$sql5) or die(mysqli_error($con));
        $row5 = mysqli_fetch_assoc($result5);
        $total_count += $row5['total']; // add counts to variable
    }
    echo $total_count; // print final count
?>

Your code is wide open for SQL INJECTION. try to use prepared statements

mysqli_prepare()

PDO::prepare

Note:- Try to do it without loop

https://dba.stackexchange.com/a/102345

like image 93
Anant Kumar Singh Avatar answered Mar 08 '26 17:03

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!