Introduction
I have been searching the internet for guide how to make a script to show how many users are connected. However, i didn't manage to find one, so i made it myself.
I am creating this guide for people who also aren't really experienced with PHP and is searching for something like this. This script may be a mess, but it works. :)
Creating a column in database
You have to create a new column in table (preferably at the end of a table). I used column named "online", so i will do the same here.
Important: Don't forget to edit your register.php and add one more ,' ' in registration code...
Editing login.php (it is going to change online column value from 0 to 1)
Since i think, that you already created database connection in login script, i think that this will be enough to show you. Thus, you should add it before you echo that login was successful.
Code:// inserting online state mysql_query(" UPDATE yourtable SET online='1' WHERE username='$username'" ) or die(mysql_error());
Editing logout.php (from 1 to 0)
I think that you haven't made any connections to database in this file, so i will include the whole code.
Code:<?php session_start(); //File which connects to database and selects table include 'db_connect.php'; //Since my session is based on persons username... This code selects the user which is doing this proccess... (i think you already know that) $user = $_SESSION['username']; $query = mysql_query("SELECT * FROM yourtable WHERE username='$user'"); $numrows = mysql_num_rows($query); // Inserting offline state mysql_query(" UPDATE yourtable SET online='0' WHERE username='$user'" ) or die(mysql_error()); session_destroy(); echo "You have been logged out."; ?>
Users_online.php script
Checks how many rows of "online" column is set to 1 and gives the answer. Answer is the count of online (logged-in) users. :)
Code:<?php session_start(); include 'db_connect.php'; $query = mysql_query("SELECT * FROM yourtable WHERE online='1'"); $numrows = mysql_num_rows($query); echo $numrows; ?>
Sorry for my bad english, if you think that it is THAT bad ;DD
And hope this will save some time for newbies at PHP. :)




Reply With Quote![[PHP & MySQL] Realtime users online script](http://ragezone.com/hyper728.png)


