<?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];
?>
在这段代码中,我为 $idd
使用了 explode 函数,并在 foreach 循环内运行查询,并希望在 foreach 循环内对多个查询求和,现在,我的查询如下所示:
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'
但是我想要这样
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
那么,我该怎么做呢?请帮助我。
谢谢
最佳答案
您需要在 foreach()
中获取值并将它们相加。像下面这样:-
<?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
?>
您的代码对SQL INJECTION
是开放的。尝试使用准备好的语句
注意:-尽量不要循环
关于php - 如何在foreach循环内求和计数查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52108777/