Create Table 'User _ online '(
'Session' Varchar ( 100 ) Not Null Default '' ,
'Time' Int ( 11 ) Not Null Default ' 0 '
) Type = MyISAM;
Code
<? PHP
Session_start ();
$ Session = Session_id ();
$ Time = Time ();
// $ Time_check is used to detect timeout
$ Time_check = $ Time - 600 ; // Set the time to 10 minutes = 10*60 seconds
$ Host = " Localhost " ; // Host Name
$ Username = " Root " ; // MySQL U User Name
$ Password = " 123456 " ; // MySQL password
$ Db_name = " Test " ; // Database Name
$ Tbl_name = " User_online " ; // Table Name
// Connect to the server and select the database
Mysql_connect ( " $ Host " , " $ Username " , " $ Password " ) Or Die ( " Unable to connect to MySQL Service " );
Mysql_select_db ( " $ Db_name " ) Or Die ( " Unable to select database " );
$ SQL = " Select * from $ Tbl_name Where session =' $ Session ' " ;
$ Result = Mysql_query ( $ SQL ); // Execute Query
$ Count = Mysql_num_rows ( $ Result );
// Check whether the specified session exists. Otherwise, insert a record.
If ( $ Count = " 0 " ){
// The specified session does not exist.
$ Sql1 = " Insert $ Tbl_name (Session, time) values (' $ Session ',' $ Time ') " ;
$ Result1 = Mysql_query ( $ Sql1 ); // Insert
} Else {
$ Sql2 = " Update $ Tbl_name Set Time =' $ Time 'Where session =' $ Session ' " ;
$ Result2 = Mysql_query ( $ Sql2 ); // If yes, modify the connection time.
}
$ Sql3 = " Select * from $ Tbl_name " ;
$ Result3 = Mysql_query ( $ Sql3 );
$ Count_user_online = Mysql_num_rows ( $ Result3 ); // The number of sessions is counted to determine the number of online users.
Echo " Online users: $ Count_user_online " ;
// Delete the timeout session record. The user connected 10 minutes ago is deemed to have timed out.
$ Sql4 = " Delete from $ Tbl_name Where time < $ Time_check " ;
$ Result4 = Mysql_query ( $ Sql4 );
Mysql_close ();
// Open multiple browsers to test
?>
Auto: http://hi.baidu.com/fanglor/blog/item/55eb194bbb9026fc83025c5c.html