php - 如何在 foreach 循环中求和计数查询?
问题描述
<?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];
?>
在这段代码中,我使用了explode函数$idd
并在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
. 尝试使用prepared statements
注意:-尝试不循环
推荐阅读
- amazon-web-services - 带有 docker 应用程序的 AWS Elastic Beanstalk 返回 502
- python - 学习 Python - 数字游戏
- r - 当我将我的 excel 文件上传到 R 时,列标题在行中,数据似乎都很混乱。我该如何解决?
- r - 将.txt格式的混合表文件拆分为两个表文件
- shopify - Shopify Debut Theme - 在精选系列主页上显示最大变体价格
- python - Python 以什么顺序查找语法错误?
- angular - 量角器 - Angular 应用程序超时错误
- python - JSONDecodeError:期望值第 6 行第 1 列(字符 5)LSTM 代码
- dataframe - 将函数应用于 PySpark 数据框中的列
- php - Laravel Blade 包括:如何将变量从孩子传递给父母?