Display Users Online Based On Page Viewing - The Code Explained (contd.)
(Page 3 of 4 )
The next part of the code looks like this:
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='$PHP_SELF'");
if(!($result)) {
print "Useronline Select Error > ";
} This PHP code and MySQL query selects the IP address from the database and looks at the current page that the user is browsing (PHP_SELF). We do it this way so as to display the number of users online in the next part of the script.
The if statements in the past few clips of code are error checking statements. The exclamation point (!) simply represents NOT FOUND or NULL
Continuing on, we have the following code:
$user = mysql_num_rows($result);
mysql_close();
if($user == 1) {
print("<b>$user</b> user online\n");
} else {
print("<b>$user</b> users online\n");
}
?> The variable $user simply counts the number of rows left in the useronline table and this in turn represents the number of users that are currently online. Pretty simple right?
Finally, our PHP code closes the MYSQL database connection and then pdisplays the number of users online using the print function. If only one user is online then the script will output "1 user online", however if there is more than one user online (for example, 5), then the script will output "5 users online".
For the more advanced PHP coders out there, we could've used something like this instead of our if block:
print "$user user" . ($user == 1 ? "" : "s") . " online";Next: Conclusion >>
More MySQL Articles
More By Stan Crawford