Friday, February 25, 2011

php who is online now?

Step1: Creating the database
create a new database called 'users', with 3 fields inside a table. These fields are timestamp, ip and file. Name the table useronline by the way. Now with the form on the PhpMyAdmin page, add the following code:

view source
print?
1 CREATE TABLE useronline (
2 timestamp int(15) DEFAULT '0' NOT NULL,
3 ip varchar(40) NOT NULL,
4 file varchar(100) NOT NULL,
5 PRIMARY KEY (timestamp),
6 KEY ip (ip),
7 KEY file (file)
8 );

Step 2: The PHP Script
view source
print?
01 ";
24 }
25
26 //delete values when they leave
27 $delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp<$timeout"); 28 if(!($delete)) { 29 print "Useronline Delete Failed > ";
30 }
31
32 //grab the results
33 $result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='$PHP_SELF'");
34 if(!($result)) {
35 print "Useronline Select Error > ";
36 }
37
38 //number of rows = the number of people online
39 $user = mysql_num_rows($result);
40
41
42 //spit out the results
43 mysql_close();
44 if($user == 1) {
45 print("$user user online\n");
46 } else {
47 print("$user users online\n");
48 }
49 ?>

I've tried to make that code as simple as possible to understand. The //comment won't affect the script, so you can remove those if you want. The script basically works like this. It receives server information and gets he time. In mySQl it fills in the values of the person online and puts up a message if it failed. When the user leaves mySQL deletes the user and displays a message if it failes.

No comments:

Post a Comment