简体   繁体   中英

Time Calculation in PHP using MySQL Query

I have a report to build in PHP where I need time difference times hourly rate for an employee pay.

For example:

Employee     Clock-In           Clock-Out     Total-Hours  Rate  Salary
Mike    2015-01-01 22:57:09 2015-01-02 11:48:14 12:51:05    10  128.51
Mike    2015-01-03 11:48:51 2015-01-06 22:19:27 82:30:36    10  825.10
Mike    2015-01-06 21:19:40 2015-01-06 22:00:00 00:40:20    10  6.72

My query is below

SELECT tt.id,ts.fname,tt.punch_in,tt.punch_out,
SEC_TO_TIME(TIMESTAMPDIFF(SECOND,tt.punch_in,tt.punch_out)) as working_hours_new,ter.hourlyrate,
((SUBSTRING(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,tt.punch_in,tt.punch_out)),1,2) + SUBSTRING(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,tt.punch_in,tt.punch_out)),4,2)/60 + SUBSTRING(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,tt.punch_in,tt.punch_out)),7,2)/3600) * ter.hourlyrate) as pay
from tbl_times as tt left join tbl_server as ts on ts.serverid = tt.user_id left join tbl_employee_rates as ter on ter.userid=tt.user_id 
where ts.locationid = ? and ts.active = 1 and ter.stauts = 1 and date(punch_in) >=  ? and date(punch_out) <= ?

If this is not an easy way to do, should I do it in PHP... any suggestions?

Each programming language or a system is designed to do a certain amount of activities in a proper manner meanwhile not so much for other activities.

SQL is designed to handle a set of certain activities .

If your task is a subset of that set then you should complete your task by using SQL, unless you can specifically find a programming language or a system that is designed to do it in a more proper way .

In your case you're relying on joins , filtering data , etc, which SQL is speficially designed to handle -- so you should definitely be doing it with SQL.

Consider wrapping your codes in functions, packages or views to make your queries reusable for all systems.

为什么不尝试:(假设为mysql)

((UNIX_TIMESTAMP(tt.punch_out) - UNIX_TIMESTAMP(tt.punch_in)) / 3600) * ter.hourlyrate AS salary

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