AngularJS+PHP帖子评论展示异常:仅显示单条评论求助
Hey there! Let's get to the bottom of why only one comment is showing up for your post ID 1 (even though you know there are 69 linked to it). Here are the most common issues and fixes based on typical code patterns:
1. Your script is only fetching the first comment from the database
If you're using a database query, chances are you're using a method that returns a single result instead of all matching comments. For example:
- Bad (Python + SQLite/MySQL):
# Only grabs the first comment cursor.execute("SELECT content FROM comments WHERE post_id = %s", (post_id,)) comment = cursor.fetchone() # This gets just one row - Good:
# Fetch all comments and loop through them cursor.execute("SELECT content FROM comments WHERE post_id = %s", (post_id,)) all_comments = cursor.fetchall() for comment in all_comments: # Render or print each comment here print(f"- {comment[0]}")
2. Your template isn't looping through the comment list
If you're using a template engine (like Jinja2, Blade, or EJS), you might be referencing a single comment variable instead of iterating over the full list. For example:
- Bad (Jinja2):
<!-- Only shows one comment --> <div class="comment">{{ post.single_comment.content }}</div> - Good:
<!-- Loops through every comment for the post --> {% for comment in post.comments %} <div class="comment"> <p>{{ comment.content }}</p> </div> {% endfor %}
3. Your SQL JOIN is grouping results incorrectly
If you're joining posts and comments in one SQL query, using GROUP BY post.id will collapse all comments for a post into a single row. For example:
- Bad SQL:
-- GROUP BY returns only one comment per post SELECT posts.title, comments.content, COUNT(comments.id) AS comment_count FROM posts LEFT JOIN comments ON posts.id = comments.post_id GROUP BY posts.id - Fix:
Split the queries: first fetch all posts, then for each post, run a separate query to get all its comments. This keeps your data clean and avoids grouping issues.
4. Double-check your comment data association
Quick sanity check: run this SQL query directly in your database to confirm the comments are actually linked to post ID 1:
SELECT * FROM comments WHERE post_id = 1;
If this returns 69 rows, then the issue is in your code. If not, you might have a data entry problem (like incorrect post_id values in the comments table).
If you can share a snippet of your code (the part where you fetch comments and render them), I can help pinpoint the exact issue even faster!
内容的提问来源于stack exchange,提问作者Markjames11

