Showing online members using PHP MySQL

Showing online members using PHP MySQL

Wall scripts are very popular nowadays. Social networks, forums and even certain web application websites have started implementing wall scripts. Wall scripts are powerful technique to store and display data relevant to a particular user on his or her, own profile page.

This means whenever you visit Facebook, Twitter or Google Plus for example, you are viewing a wall script – the script that produces your wall’s feed. Showing online members is a concept that was adopted way before wall script and social technology ideas. This concept first evolved with the idea of chat rooms.

Whenever you log into a system, you would naturally want to look out for other people who are also logged in at the same time. Isn’t it? Well, for me it is a very curious stuff as to how do these major websites implement this idea?

One day I figured out a very simple method of implementing this concept. I was working on my college project then. I was building a web application on social networking. I tried it out and it actually worked!

This procedure might be different from what the major websites implement, but I can assure you that if you are a beginner and want to implement this concept with the minimum amount of hassles – this is it. I have even tried it over multiple systems through LAN and it worked perfectly.

Concept of showing online members

Let us get the basic concept first. We need to show members who are logged in at the moment. Say for example, a green border appears beside the profile picture to show that they are online.

Now, the profile page gets generated through PHP in our example. PHP generates dynamic data and feeds it into the static HTML. Read more on Difference between static dynamic content.

What we need to check is whether any other user is logged in at the moment. If they are, then they are displayed in the list with a green border. How to check? I’ll tell you exactly how to do that in a simple way.

Plan the HTML structure of showing online members

Wall scripts and even chat applications have a friend list or something like that to show online members. So, when a list is displayed containing all friends or connections of the currently logged in user; the list helps in showing online members and offline members. In our case, we do the same.

First create your HTML structure to show a list of usernames that are in the current user’s connections. Each user structure will contain an image of the connection and the name. So, here’s a demo structure I have prepared. Have a look –

      • ”some Some Name

 

So, this becomes our basic structure. The “li” items are iterated through PHP loop to generate all relevant users. The image source and name comes dynamically. I have opted out the CSS part in this article because we are focusing more on the PHP code.

Notice at this point that we have included a class for the “li” item. So, when they are iterated each “li” item shall have a class. This class shall determine the styling of the list.

We shall have two classes. Both the classes shall be same except for one attribute – the border. So, let’s say we have two classes called “online” and “offline”. The styling would differ as the following –

.online, .offline {
// mention all styling here including width, margin, etc.
}
.online{
border-left: 3px solid green; 
}
.offline{
border-left: 3px solid grey; 
}

The class “online” shall be fed as class name to the “li” element when the PHP code confirms that a particular record is online at that moment – thus showing online members.

The backend code for showing online members

Once we are ready with structures, our next step is to add dynamic content.

First, we create a separate table in our database. This is the first step of our procedure. This table shall contain the user’s login information. The database table shall have two fields – userid and loginstatus (you might name them as you like).
Let us create the database table first –

$query="CREATE TABLE IF NOT EXISTS online_status (
userid int(10), loginstatus int(3)
)";
        $results = mysql_query($query)
        or die(mysql_error());

Now, the next step is whenever a user logs in to the system create a record for him or her in this table. So, after the login authentication is complete create a SESSION variable to store the userid of this user. At the same time, insert a row in the above table (online_status) with the user’s id as userid and loginstatus as 1. Now, proceed to the profile page.

Similarly, when a user logs out this particular record must be searched and deleted with a query. This is to make sure that when the user logs out his status is updated. Don’t forget this step. This very important!

So, in this way whenever a user logs in, his or her record is created in that table. Now, in the profile page we call dynamic data. Our friend list HTML is ready. The code fetches all friends and connections of the current user. While fetching we also fetch the userid of these connections.

Now, this is the final step of showing online members. We have the particular friend’s id while iterating in the loop. We create a function to query whether this loop id matches with any record in the online_status table. If yes – the member is online or else the member is offline.

/* PHP function to return the class name of the “li” 
according user login status  */
function getStyle($userid){
$query="SELECT loginstatus FROM online_status 
WHERE userid=’".$userid.”’”;
        $results = mysql_query($query)
        or die(mysql_error());
// checking part 
if(mysql_num_rows($results)>=1){
	return ‘online’; 
}
else{
	return ‘offline’;
}
}
<!-- Now we call this function in the “li” item as follows -->

 

During the check, we provide the class name accordingly (we created two different classes for showing online members and offline ones) and the result is fantastic!

The drawbacks

Fallbacks might arise while showing online members in this procedure.

Firstly, make a note that deleting the record while logout of a user is mandatory. Otherwise you might get wrong results.

Secondly, one common issue that I faced was when a user does not log out and simply closes the browser – this system fails, thus producing wrong results.

Thirdly, you could also use the SQL MODIFY statement or simply the UPDATE statement if you want. But, make sure you are confident enough. When using these two you need not delete records when the user logs out.

  • Nirvik Dey

    Firstly, thank u for d photo credits…. :)

    The drawbacks can be overcomed by either using socket programming…..which is fast and reliable…but hard to code for newbie or anyone (atleast for me).

    Their is another way by which this can be overcomed….and that is you logout an user if he is idle for a long time (though u have to keep track of user activity)…

    • Your welcome Nirvik.

      And thanks for the awesome feedback. I guess the readers will take a good note of that. Your feedbacks have always been quite valuable

      Cheers!

  • Niranjan

    Hello, Kaustav Banerjee

    Really Nice job,

    If you brief the process and code it ll be helpfull

    Thank you
    Regards
    Niranjan

    • Hi Niranjan,

      Thanks for stopping by. Well, the concept is really simple. If you go through the article completely, you’ll see that I have explained it well with codes. The basic idea is you display the set of user’s in your friend list. Each will have a border on the left (or anything of that sort to show online/offline status). This border will be green if online and gray if offline.

      Now to determine whether online or offline, you’ll have to maintain a table in your database. Whenever a user logs in to your system, you either generate a session or a cookie. At the same time, you have to update this table with the user’s unique id and a status marked online.

      While displaying the user list or friend list, check this table whether the user’s id exists in this table or not. If it exists, that means he has logged in and is online. So, border will be green, otherwise gray.

      Also, when a user logs out of the system, delete the corresponding record from the table so that the system no longer shows him online.

      I hope you get it now :)