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();
?>