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

1 Answer 1

1

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

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

Comments

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.