0

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>"; 
     }
?>
12
  • Anything you want to show goes after SELECT, not HAVING Commented Sep 29, 2016 at 14:13
  • SUM(column) and not SUM('string'). dev.mysql.com/doc/refman/5.7/en/… and make sure you started the session. Commented Sep 29, 2016 at 14:13
  • 5
    Question should have been "How do I indent my code so its readable?" Commented Sep 29, 2016 at 14:13
  • i want to add these field ..these are come from 1 coulm against id Commented Sep 29, 2016 at 14:15
  • @RiggsFolly Alas, that's a common issue. Commented Sep 29, 2016 at 14:16

1 Answer 1

1

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') 
Sign up to request clarification or add additional context in comments.

3 Comments

The grouping probably isn't needed. Since the php only shows a count.
@LukStorms Maybe, but the "non-working" code make me think that it's desired. Who knows, who knows...
leave type is a column and i want to count the sum of all entries against emp id from this leave type column. like('Absent', 'Annual','Medical', 'Casual' , 'LWOP') in leavetype is 6 show as grand total

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.