What are the best practices for retrieving and displaying forum data in PHP?

When retrieving and displaying forum data in PHP, it is important to sanitize user input to prevent SQL injection and XSS attacks. Use prepared statements when querying the database to prevent SQL injection. Additionally, consider implementing pagination to improve the performance of displaying large amounts of data.

// Retrieve forum data from the database using prepared statements
$stmt = $pdo->prepare("SELECT * FROM forum_posts WHERE category = :category");
$stmt->bindParam(':category', $category);
$stmt->execute();
$posts = $stmt->fetchAll();

// Display forum data with pagination
$perPage = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $perPage;

$posts = array_slice($posts, $start, $perPage);

foreach ($posts as $post) {
    echo "<div>{$post['title']}</div>";
    echo "<div>{$post['content']}</div>";
}

// Display pagination links
$totalPosts = count($posts);
$totalPages = ceil($totalPosts / $perPage);

for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='forum.php?page=$i'>$i</a>";
}