检查用户是否在PHP中在线:我在这里做错了什么?

时间:2014-05-10 10:02:11

标签: php mysql

function checkUserStatus($uid) {
    $q = "select last_activity from signup_and_login_table where id='$uid' LIMIT 1";
    $link=mysql_connect("localhost","mydbusr","mydbpass");
        mysql_select_db("mymaindb",$link);
    $ros=mysql_query($q,$link);
    while($row=mysql_fetch_array($ros))
    {
        $last_activity =  $row['last_activity'];
        if (strtotime(date('Y-m-d H:i:s')) > strtotime($last_activity) + 30 ) {
            return false;
        } else {
            return true;
        }
    }
}

每次用户刷新页面或者执行其他操作时,我都会更新mysql上的last_activity值。

为什么上面的函数总是返回true,即使last_activity和now()之间的时差超过30秒,也永远不会返回false?

mysql中的时间以这种格式显示:2014-05-02 07:44:55

任何提示都将受到高度赞赏

3 个答案:

答案 0 :(得分:1)

如果你想使用" while Loop",你应该使用mysql_fetch_assoc()函数作为下一个:

function checkUserStatus($uid) {
    $q = "select last_activity from signup_and_login_table where id='$uid'";
    $link=mysql_connect("localhost","mydbusr","mydbpass");
        mysql_select_db("mymaindb",$link);
    $ros=mysql_query($q,$link);
    while($row=mysql_fetch_assoc($ros))
    {
        $last_activity =  $row['last_activity'];
        if (strtotime(date('Y-m-d H:i:s')) > strtotime($last_activity) + 30 ) {
            return false;
        } else {
            return true;
        }
    }
}

或者你可以不用循环尝试:

function checkUserStatus($uid) {
    $q = "select last_activity from signup_and_login_table where id='$uid' LIMIT 1";
    $link=mysql_connect("localhost","mydbusr","mydbpass");
        mysql_select_db("mymaindb",$link);
    $ros=mysql_query($q,$link);
    $row = mysql_fetch_assoc($ros);
    $last_activity =  $row['last_activity'];
    if (strtotime(date('Y-m-d H:i:s')) > strtotime($last_activity) + 30 ) {
        return false;
    } else {
        return true;
    }
}

答案 1 :(得分:0)

您应该将其更改为:

function checkUserStatus($uid) {

$q = "select last_activity from signup_and_login_table where id='$uid' ORDER BY last_activity DESC LIMIT 1";
$link=mysql_connect("localhost","mydbusr","mydbpass");
    mysql_select_db("mymaindb",$link);
$ros=mysql_query($q,$link);
$row=mysql_fetch_array($ros);

    $last_activity =  $row['last_activity'];
    if (strtotime(date('Y-m-d H:i:s')) > strtotime($last_activity) + 30 ) {
    return false;
    } else {
    return true;
    }

}

您只能选择1条记录,但可以通过last_activity DESC对其进行排序,并将其与当前时间进行简单比较

答案 2 :(得分:0)

使用 mysqli_* 功能要好得多。

function checkUserStatus($uid) {
    $q = "select last_activity from signup_and_login_table where id='$uid' LIMIT 1";
    $link = mysqli_connect("localhost","mydbusr","mydbpass");
        mysqli_select_db("mymaindb",$link);

    $res = mysqli_query($link, $q);
    $row = mysqli_fetch_num($res);//this function returns the result in a numeric array

    return time() > strtotime($row[0]) + 30;
}