drnrxv9383 2016-11-11 17:46
浏览 124
已采纳

PHP MYSQL中的SUM和循环

Well, I'm currently working on SUM and Looping array in php.

Here's my php code:

<?php

require_once 'koneksi.php';

if(isset($_POST['id_gejala'])) {
    
    $val = $_POST['id_gejala'];
    
    for($i="0"; $i < sizeof($val); $i++) {
        
        $seldata = mysqli_query($con, "SELECT a.`kode_evidence`, a.`kode_hipotesa`, a.`nilai_evidence`, b.`probabilitas`, SUM(a.`nilai_evidence`) AS `total_evidence` FROM `evidence` AS a INNER JOIN hipotesa AS b ON a.`kode_hipotesa` = b.`kode_hipotesa` WHERE `kode_evidence` ='".$val[$i]."' GROUP BY a.`kode_hipotesa` HAVING COUNT(*) >= 1 ") or die (mysqli_error($con));
        
        while($data1=mysqli_fetch_assoc($seldata)){
            $data[]=$data1;
        }
    }
}

$json = json_encode($data);
echo $json;

?>

I've successfully generated the json response when I echo $json, here's the response I get:

[
{
"kode_evidence":"1",
"kode_hipotesa":"1",
"nilai_evidence":"0.9",
"probabilitas":"0.09",
"total_evidence":"0.8999999761581421"
},
{
"kode_evidence":"2",
"kode_hipotesa":"1",
"nilai_evidence":"0.4",
"probabilitas":"0.09",
"total_evidence":"0.4000000059604645"
}
]

In my php code, the GROUP BY and HAVING COUNT command in sql variable are not working, I still get 2 responses and the result won't do the sum of nilai_evidence.

I need to get only 1 result from post and the do the SUM calculation of the query.

Any help will be much appreciated, thank you.

</div>
  • 写回答

1条回答 默认 最新

  • doulu8341 2016-11-11 17:54
    关注

    You are using aggregation function only on a part of the column that you set in group by ..

    this could retrive unrelated value for this column respctec the value for ggregated function

    Could be that for your query the valeue of the column in these column is the same
    when you could use (fake ) aggregation function for avoid the return of more that one row

      "SELECT 
              min(a.`kode_evidence`)
            , a.`kode_hipotesa`
            , min(a.`nilai_evidence`)
            , min(b.`probabilitas`)
            , SUM(a.`nilai_evidence`) AS `total_evidence` 
      FROM `evidence` AS a 
      INNER JOIN hipotesa AS b ON a.`kode_hipotesa` = b.`kode_hipotesa` 
      WHERE `kode_evidence` ='".$val[$i]."' 
      GROUP BY a.`kode_hipotesa` 
      HAVING COUNT(*) >= 1 ") or die (mysqli_error($con));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型