1

I have two tables, one with posts and another one with comments:

posts
-----
ID
user_ID
text
date

comments
--------
ID
post_ID
user_ID
text
date  

I want to display every post and for each post, I want to display the related comments. So I made two queries:

include('bdd.php');
$reponse = $bdd->query('
    SELECT posts.ID AS post_ID, posts.user_ID, posts.text, posts.date FROM posts
    ORDER BY posts.ID DESC
');
while ($post = $reponse->fetch()){
    //displaying a post
    $get_comments=$bdd->query('SELECT * FROM comments WHERE post_ID ='.$post['post_ID']);
    while($comment = $get_comments->fecth()){
         //displaying a comment
         echo $comment['text']
    }
}

But the code stops and only displays the first post without the comments.

6
  • are you using PDO? Try to insert $reponse->execute(); before first while. OR replace $bdd->prepare(); with $bdd->query(); Commented Sep 29, 2013 at 11:09
  • Yes, you're right, I forgot it when I simplified the code, I just added it. It doesn't solve the problem. Thanks anyway. Commented Sep 29, 2013 at 11:48
  • i am posting it as answer, accept it. happy coding Commented Sep 29, 2013 at 11:49
  • No, don't. It doesn't solve the problem, it still doesn't work. Sorry if I wasn't clear enough. Commented Sep 29, 2013 at 11:52
  • make sure the post your displaying must have some comments on your database.Test your mysql query and loop. your code is ok. use echo $bdd->rowCount(); to check numbers of rows selected Commented Sep 29, 2013 at 11:56

2 Answers 2

2

Try to insert

 $reponse->execute();

before first while. OR replace $bdd->prepare(); with $bdd->query();

Typo error:

$get_comments->fecth() check your fetch() spelling

Sign up to request clarification or add additional context in comments.

1 Comment

It was the spelling mistake. Thank you!
1

is the select query even correct??

SELECT posts.ID AS post_ID, posts.user_ID, posts.text, posts.date
ORDER BY posts.ID DESC

It has no FROM clause. Should have been as below:

SELECT posts.ID AS post_ID, posts.user_ID, posts.text, posts.date FROM posts
ORDER BY posts.ID DESC

1 Comment

You're right, infact, I simplified the code, and I forgot the FROM. But that's not the problem. Thanks anyway. I added the FROM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.