简体   繁体   English

使用PHP计算在线用户数量

[英]Count amount of online users with PHP

I'm trying to count how many users are online on my site within 10 minutes and display it, but I'm facing some problems with my code. 我试图计算在10分钟内我的网站上有多少用户在线并显示它,但是我的代码遇到了一些问题。

//Count online users
//Data on DB: 2016-06-08 03:15:21

    $onlinesql = $odb -> prepare("SELECT `users`.`lastactivity`  count(*) FROM `users` WHERE `lastactivity` >= DATE_SUB(NOW(), INTERVAL 10 MINUTE");
    $onlinesql -> execute(array(":id" => `lastactivity`));
    $rowonline = $onlinesql -> fetch(); 

    echo $rowonline;

It's not returning the number of online users, how can I get it working? 它没有返回在线用户的数量,我如何才能使它正常工作?

SELECT count(*) FROM `users` WHERE `lastactivity` >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)

无需使用count( id )或count( lastactivity ),只需使用count(*),因为这是最快的方法

You may want to revisit your SQL. 您可能想重新访问您的SQL。 Here's an Example: 这是一个例子:

    <?php    
        $sql        = "SELECT COUNT(U.*) FROM `users` U WHERE u.lastactivity >= DATE_SUB( NOW(), INTERVAL 10 MINUTE)";
        $onlineSQL  = $odb ->prepare($sql);
        $onlineSQL  -> execute();
        $numOnline  = $onlineSQL->fetch();

        var_dump($numOnline);

You can use ajax. 您可以使用ajax。 create an enum field in users table lets call it (status) '0'=> offline and '1'=> online and make two setInterval functions one to update user status each 2 minutes for example with ajax and another one to get count of users with status '1' from database with ajax too. 在users表中创建一个枚举字段,让它(状态)为'0'=> offline和'1'=> online,并创建两个setInterval函数,一个函数每隔2分钟更新一次用户状态,例如用ajax更新,另一个函数获取计数带有ajax的数据库中状态也为“ 1”的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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