简体   繁体   中英

Displaying amount of users on a webpage

I am trying to write a PHP script that will count the amount of users that have visited the page within the last 10 minutes. This is my script right now:

function getOnlineUsers($database, $main_connection){

    $database;

    $visitor_id = session_id();

    $timestamp = time();
    $timeOut = $timestamp - 6000;

    mysql_query("INSERT INTO online (m_time, ip) VALUES ('$timestamp', '$visitor_id')", $main_connection);
    mysql_query("DELETE FROM online WHERE m_time < $timeOut");

    $result = mysql_query("SELECT * FROM online");
    mysql_fetch_assoc($result);
    if(!$result){
        $online_users = 1;
    }else{
        $online_users = mysql_num_rows($result);
    }

    return $online_users+1;
}

The problem is that nothing is being inserted into the database and the database remains empty and therefore the count is null. Can someone please assist me in this?

First, better use PDO or MySQLi. In your database, the 'm_time' column must be integer type, and pass the $timestamp value as number, not within quotes.

"INSERT INTO online (m_time, ip) VALUES ($timestamp, '$visitor_id')"

1) Change '$timestamp' to NOW(), mysql can't understand php's time() function ( assuming m_time is a datetime field) .

ie:

INSERT INTO online (m_time, ip) 
 VALUES ( NOW(), '$visitor_id')

2) Your delete suffers the same problem

3) You can use something a little more clever to get the users in the last 10 minutes, try something like:

select count(*) AS OnlineUserCount 
 from online 
WHERE 
 m_time > DATE_SUB( NOW(), INTERVAL 10 MINUTE ) ;

Your code looks fine .. what i suggest you do is echo out the query when it runs and cope and paste it and run it directly from phpmyadmin and check if it gives you any error and if the row is inserted succesfully i suggest you check your connection file with the database.

And also try what's suggested by CoursesWeb

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