What are the best practices for incorporating a comment function similar to Facebook on a PHP website?

When incorporating a comment function similar to Facebook on a PHP website, it is important to ensure proper validation and sanitization of user input to prevent XSS attacks. Additionally, implementing a system for users to report inappropriate comments and moderating comments before they are displayed can help maintain a positive user experience.

// Sample PHP code snippet for incorporating a comment function on a website

// Validate and sanitize user input
$comment = htmlspecialchars($_POST['comment']);
$user_id = $_SESSION['user_id'];

// Insert comment into database
$query = "INSERT INTO comments (user_id, comment) VALUES ('$user_id', '$comment')";
$result = mysqli_query($conn, $query);

if($result) {
    echo "Comment posted successfully!";
} else {
    echo "Error posting comment. Please try again.";
}