Muhammad Usman
Muhammad Usman

Reputation: 29

how to sum in foreach loop in php

this is my code i want the sum of the fields but unable to do this any one can help in this regards

<?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>"; 
     }
?>

Upvotes: 0

Views: 68

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

HAVING is a filter on grouped results, not a way to select anything

I would guess you need something like

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

If you want only the count of all these leavetypes, just do

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

Upvotes: 1

Related Questions