php - 如何在foreach循环内求和计数查询?

标签 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

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

谢谢

最佳答案

您需要在 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 是开放的。尝试使用准备好的语句

mysqli_prepare()

PDO::prepare

注意:-尽量不要循环

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

关于php - 如何在foreach循环内求和计数查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52108777/

相关文章:

php - DOMDocument 破坏编码?

php - 用文本间隔替换数字间隔

php - 如何在 PHP 中使用 file_get_contents() 请求移动版本?

php - 如何关联 php mysql 中不同表的值并显示这些值?

php - mySQLi 准备失败,多个?从形式

php - 创建安全的 MYSQLI 登录脚本?

java - 在 Java 中不断检查和读取 PHP 文件以了解数据库更改的最简单/最有效的方法?

php - Uncaught Error : Class 'ComposerAutoloaderInit' not found

php - MySqli 准备好的语句在执行语句时不使用更新的变量值

php - 表单数据插入数据库后如何清空