如何在foreach循环中求和计数查询?

时间:2018-08-31 05:08:20

标签: php mysqli

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

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

谢谢

1 个答案:

答案 0 :(得分:0)

您需要在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::prepare

注意:- 尝试无循环执行

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