Online Users script using PHP and MySQL


While surfing internet you may have seen many websites which displays the number of online users. In this post we are going to learn how to create the similar script using PHP and MySQL.But before reading  this  post further,if you haven’t read my previous post then please have a look at “Visitors Counter Script”.After reading  that post your basic concepts regarding this will gets more clear.


This script is very simple and has only two steps which are as below.

Step: 1 Create table : “online_users”


CREATE TABLE `online_users` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'
) TYPE=MyISAM;

Step:2 Create file : online_users.php

<?php
session_start();
$session=session_id();
$time=time();
$time_check=$time-300; //We Have Set Time 5 Minutes

$host="localhost"; // your Host name
$username="root"; // your Mysql username
$password=""; // your Mysql password
$db_name="test"; // your Databasename
$tbl_name="online_users"; // Table name

mysql_connect("$host", "$username", "$password")or die("could notconnect toserver.");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);

//If count is 0 , then enter the values

if($count=="0"){
$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}

// else update the values

else {
$sql2="UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}


$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "<b>Users Online : </b> $count_user_online ";


// after 5 minutes, session will be deleted
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);


//To see the result run this script in multiple browser.
mysql_close();

?>

That's it.! You have Done it...

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP