Skip to content
PHP Logo

How can you efficiently query and display comments that are related to specific news articles in PHP?

To efficiently query and display comments related to specific news articles in PHP, you can create a database table to store comments with a foreign key referencing the article they belong to. When querying comments, you can use a SQL JOIN statement to retrieve only the comments related to the specific article being viewed.

php
// Assuming you have a database connection established

// Query to retrieve comments related to a specific article
$article_id = $_GET['article_id']; // assuming article_id is passed in the URL
$query = "SELECT c.comment_text, u.username 
          FROM comments c
          JOIN articles a ON c.article_id = a.id
          JOIN users u ON c.user_id = u.id
          WHERE a.id = $article_id";

$result = mysqli_query($conn, $query);

// Display comments
while($row = mysqli_fetch_assoc($result)) {
    echo "<p><strong>{$row['username']}</strong>: {$row['comment_text']}</p>";
}