connect_error) { die("Connection failed: " . $conn->connect_error); } // Handle sending messages via WebSocket if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) { $message = htmlspecialchars($_POST['message']); $stmt = $conn->prepare("INSERT INTO messages (sender_id, group_id, message, timestamp) VALUES (?, ?, ?, NOW())"); $stmt->bind_param("iis", $sender_id, $group_id, $message); $stmt->execute(); $stmt->close(); // Return message with username and timestamp for WebSocket $response = [ 'username' => $_SESSION['username'], 'message' => $message, 'timestamp' => date('Y-m-d H:i:s'), 'sender_id' => $sender_id ]; echo json_encode($response); exit; } // Fetch messages for the group $stmt = $conn->prepare("SELECT users.username, messages.message, messages.timestamp FROM messages JOIN users ON messages.sender_id = users.id WHERE group_id = ? ORDER BY messages.timestamp ASC"); $stmt->bind_param("i", $group_id); $stmt->execute(); $result = $stmt->get_result(); $messages = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); // Update user status to "online" in the database $update_status = $conn->prepare("UPDATE users SET status = 'online' WHERE id = ?"); $update_status->bind_param("i", $sender_id); $update_status->execute(); $update_status->close(); // Fetch all users for online status display $users = $conn->query("SELECT username, status FROM users"); ?> Group Chat with Online Status

Online Users

:
prepare("UPDATE users SET last_activity = NOW() WHERE id = ?"); $update_status->bind_param("i", $sender_id); $update_status->execute(); $update_status->close(); } // Mark users as offline if they haven't been active for more than 10 minutes $conn->query("UPDATE users SET status = 'offline' WHERE TIMESTAMPDIFF(MINUTE, last_activity, NOW()) > 10"); // Update the user's status when leaving register_shutdown_function(function() use ($conn, $sender_id) { $stmt = $conn->prepare("UPDATE users SET status = 'offline' WHERE id = ?"); $stmt->bind_param("i", $sender_id); $stmt->execute(); $stmt->close(); }); $conn->close(); ?>