PHP / MySQL - 使用查询结果在另一个查询中使用

时间:2013-09-29 10:43:12

标签: php mysql sql while-loop fetch

我有两个表,一个有帖子,另一个有评论:

posts
-----
ID
user_ID
text
date

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

我想显示每个帖子和每个帖子,我想显示相关的评论。所以我提出了两个问题:

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']
    }
}

但是代码停止了,只显示没有评论的第一篇文章。

2 个答案:

答案 0 :(得分:2)

尝试插入

 $reponse->execute();

在第一个while之前。或替换 $bdd->prepare();$bdd->query();

。{

错误错误:

$get_comments->fecth()检查您的fetch()拼写

答案 1 :(得分:1)

是选择查询甚至是正确的吗?

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

它没有FROM子句。应该如下:

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