omkara
omkara

Reputation: 982

How to sum count query inside foreach loop?

<?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

Upvotes: 3

Views: 1166

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

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

Upvotes: 1

Related Questions