简体   繁体   中英

Loop through SQL and calculate sum in PHP

I have an issue with my code. I have 2 tables. First employee_id:

|Employee id|

1

2

3

And the second table called employee_times:

|Employee_id|Hours_dev|hours_pm|

|1|2|3|

|1|3|4|

|2|3|3|

What I am trying to do is to calculate the total time that each employee has worked (hours_dev+hours_pm). For example employee_id 1 has worked 12 hours

So far I have tried to retrieve all the employee_id from the first table and use a for loop to go through the employee_times in an SQL statement (SEE CODE BELOW). However the code does not work as it prints 0 for both employee_id and total_hours.

I am using MYSQL on a localhost server.

$sql = "SELECT employee_id FROM employee"; $result = mysql_query($sql); while($row = mysql_fetch_array) { $employee_id = $row['employee_id']; }

              $employee_id_length = sizeof($employee_id);

              for($i = 0; $i < $employee_id_length; $i++)
              {
                 $sql4 = "SELECT employee_id, hours_dev, hours_pm FROM employee_times WHERE employee_id= '$employee_id[$i]'";
                        $result =  mysql_query($sql4);
                          while($info = mysql_fetch_array($result));
                        {
                            $employee_id = $info['employee_id'];
                            $hours_dev=$info['hours_dev'];
                            $hours_pm=$info['hours_pm'];
                            $total_hours = ($total_hours + $hours_dev + $hours_pm );

                        }

                        //print "$employee_id worked for $total_hours";
              }

Any help is much appreciated.

you can get sum directly

 select employee_id, sum(hours_dev)+ sum(hours_pm) as total 
from employee_times WHERE employee_id= '1'
group by employee_id

refer this Fiddle Demo

this should get the data you need

SELECT
  hours_dev,
  hours_pm,
  sum(hours_dev) + sum(hours_pm) as total_hours
FROM
  employee_times
WHERE
  employee_id = 123
GROUP BY
  employee_id

This SQL query should pull the info much quicker than by script;

SELECT Employee_id, SUM(Hours_dev), SUM(Hours_pm), SUM(Hours_dev + Hours_pm) 
FROM employee_times 
GROUP BY Employee_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM