I would appreciate it if someone could help me with some logic here on how to turn my timestamp function into a working payroll service.

Right now when a user logs in to my site, they can click a clock in button which timestamps the datetime format into SQL.

This is the format: 2013-05-12 09:19:00

  • On click, it starts the clock in the in column.
  • When they click again, it adds to the out column.

It is storing in these columns:

  • id (auto_increment)
  • userid (unique)
  • in (datetime)
  • out (datetime)

How would a function look / work to grab total hours clocked from an employee?

At the least, point me in the right direction to resolve this scenario please.

有帮助吗?

解决方案

You can take advantage of the MySQL functions SUM and TIMESTAMPDIFF to calculate it for you:

SELECT SUM(TIMESTAMPDIFF(HOUR, `in`, `out`)) AS hours
  FROM myTable
 WHERE userid = 1

Live DEMO

其他提示

I would select all rows with the user id, and in PHP would get function like this:

$time = 0;
while($row = $query->fetch_object())
{
    $time += (strtotime($row->out) - strtotime($row->in));
}

And then $time would be the total time which you can format in your favourite way.

I would use a mysql query :

select SEC_TO_TIME(SUM(TIME_TO_SEC(session_duration))) as total_session_duration
    from (
        select timediff(`in`, `out`) as session_duration 
            from employees_log #your table_name here
            where userid = [your user id]
) as t_duration

Couldn't test it, but I'm pretty sure this should work.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top