How can PHP be used to display a list of online users based on stored data in a database?
To display a list of online users based on stored data in a database, we can create a PHP script that queries the database for users who are currently online. We can achieve this by storing a timestamp of the user's last activity in the database and comparing it to the current time to determine if the user is online. The script can then fetch and display the list of online users.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query the database for online users
$current_time = time();
$online_threshold = $current_time - 300; // Consider users online if their last activity was within the last 5 minutes
$sql = "SELECT username FROM users WHERE last_activity > $online_threshold";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Online User: " . $row["username"] . "<br>";
}
} else {
echo "No online users";
}
$conn->close();
?>
Keywords
Related Questions
- How can the use of window.open() in PHP-generated HTML code impact cross-browser compatibility and user experience?
- What are some best practices for efficiently sorting and manipulating data in PHP arrays retrieved from MySQL?
- What is the correct syntax for retrieving form data in PHP using the POST method?