如何在PHP中的foreach循环中求和

时间:2016-09-29 14:11:22

标签: php sql

这是我的代码我想要字段的总和但无法做到这一点任何人都可以在这方面提供帮助

<?php
     $hostname="localhost";  
     $username="root";  
     $password="";  
     $db = "usman";  

     $dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);  

     foreach($dbh->query("SELECT COUNT(*) as cnt
     FROM ams 
     WHERE empid= {$_SESSION['sess_user_id']} 
     GROUP BY leavetype 
     HAVING leavetype =               
     sum('Absent'), sum('Annual'),sum('Medical'), 
     sum('Casual') , sum('LWOP') ") as  $GrandTotal) 
     {  
           echo "<table ><tr ><td style='border: 0px; ' >" .        
           $GrandTotal['cnt'] . "</td></tr></table>";    
           echo "<br>"; 
     }
?>

1 个答案:

答案 0 :(得分:1)

HAVING是对分组结果的过滤器,而不是选择任何内容的方法

我猜你需要像

这样的东西
SELECT 
  leavetype, 
  count(*) as cnt
FROM ams 
 where empid= {$_SESSION['sess_user_id']} 
 and leavetype in ('Absent', 'Annual','Medical',  'Casual' , 'LWOP') -- if you want only certain leave types
GROUP BY leavetype

如果您只想要所有这些留言类型的计数,请执行

SELECT 
 count(*) as cnt
FROM ams 
where empid= {$_SESSION['sess_user_id']} 
and leavetype in ('Absent', 'Annual','Medical',  'Casual' , 'LWOP')