首页 > 解决方案 > 如何在 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

那么,我该怎么做呢?请帮我。

谢谢你

标签: phpmysqli

解决方案


您需要在其中获取值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

mysqli_prepare()

PDO::准备

注意:-尝试不循环

https://dba.stackexchange.com/a/102345


推荐阅读