PHP / MYSQL认证登录/登出时间的总和

时间:2012-07-17 04:53:09

标签: authentication logging login logout

我有一个简单的身份验证日志格式化为mysql,如下所示:


用户名| login_time | last_active

鲍勃| 2012-01-01 22:00:00 | 2012-01-02 06:00:00

鲍勃| 2012-01-02 08:00:00 | 2012-01-02 09:00:00

鲍勃| 2012-01-02 23:00:00 | 2012-01-03 10:00:00


现在,我正在尝试显示用户在这些时间范围内工作的总时数:

0-24小时前

24-48小时前

48-72小时前


对于24-48例子,我最初编码:

$start_time = date("Y-m-d H:i:s", strtotime("-2 days"));
$end_time = date("Y-m-d H:i:s", strtotime("-1 days"));
$result_time = mysql_query("SELECT login_time,last_active FROM `auth_log` WHERE username = '".$row['username']."' AND login_time > '$start_time' AND login_time <= '$end_time' AND authenticated = 'yes'");
    while($row_time = mysql_fetch_array( $result_time )) {
        $time = strtotime($row_time['last_active']) - strtotime($row_time['login_time']);
        $tot_time = $tot_time + $time;
    }
$total_time = gmdate('H:i',$tot_time);

如果我们的24-48小时时间截止时间是:2012-01-02 00:00:00和2012-01-03 00:00:00那么,如上面的数据库表所示,第1行和第3行不会包含在查询中。仅显示落在截止时间内的记录(第2行)。因此,这表明鲍勃工作了1小时,事实上,鲍勃在24-48小时的时间内总共工作了8个小时。 (从第1行+ 1小时第2行+第1行第3行开始6小时)

所以现在我有点卡住了。

我认为必须有一种更简单的方法来做到这一点。要么我的身份验证数据库设计很糟糕,要么使用mysql时间/日期查询更容易获取此信息,否则我将不得不进行非常复杂的查找,如:

$start_time = date("Y-m-d H:i:s", strtotime("-2 days"));
$end_time = date("Y-m-d H:i:s", strtotime("-1 days"));
$result_time = mysql_query("
SELECT login_time,last_active FROM auth_log 
WHERE username = '$username' 
AND authenticated = 'yes'
AND (login_time >= '$start' AND last_active <= '$end') 
OR (login_time >= '$start' AND login_time <= '$end' AND last_active > '$end') 
OR (last_active >= '$start' AND last_active <= '$end' AND login_time < '$start') 
");

任何帮助肯定会受到赞赏!

1 个答案:

答案 0 :(得分:0)

$day_index = SELECT WEEKDAY(\''.$date.'\') AS day_index;

SELECT SEC_TO_TIME( SUM( t.diff ) ) AS suma
FROM (
    SELECT login_time, TIME_TO_SEC( TIMEDIFF( logout_time, login_time ) ) AS diff
    FROM login_times
    WHERE user_id = '.$id.'
    AND DATE( login_time ) = SUBDATE(\''.$date.'\', '.$day_index.' )
) AS t
GROUP BY DATE( t.login_time )'

我有类似你的表,这个查询正确处理选择,而不是名称user_id