How can PHP be used to track and display user activity in a forum setting?

To track and display user activity in a forum setting using PHP, you can create a logging system that records user actions such as posting, commenting, liking, etc. This logging system can store data in a database table and then use PHP to retrieve and display this data on the forum site.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "forum";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Log user activity
$user_id = $_SESSION['user_id'];
$action = "posted a comment";
$timestamp = date('Y-m-d H:i:s');

$sql = "INSERT INTO user_activity (user_id, action, timestamp) VALUES ('$user_id', '$action', '$timestamp')";

if ($conn->query($sql) === TRUE) {
    echo "User activity logged successfully";
} else {
    echo "Error logging user activity: " . $conn->error;
}

// Display user activity
$sql = "SELECT * FROM user_activity ORDER BY timestamp DESC";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "User " . $row['user_id'] . " " . $row['action'] . " at " . $row['timestamp'] . "<br>";
    }
} else {
    echo "No user activity found";
}

$conn->close();