Php 如何在foreach循环内对计数查询求和?

Php 如何在foreach循环内对计数查询求和?,php,mysqli,Php,Mysqli,但是我想要这样 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' 那么,我该怎么做呢?请帮帮我 谢谢您需要获取foreach()中的值并求和。你可以这样做:- select (select count(DISTINCT pr

但是我想要这样

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'
那么,我该怎么做呢?请帮帮我


谢谢

您需要获取
foreach()中的值
并求和。你可以这样做:-

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

您的代码对于
SQL注入
是完全开放的。尝试使用
准备好的语句

注意:-尽量不使用循环

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