假设我有一些帖子,这些帖子包含评论,一些帖子有超过 1 条评论,而另一些只有 1 条评论。
我必须从该帖子的用户那里获取所有数据,并从对该帖子发表评论的人那里获取用户信息。现在说我必须回显所有这些数据。我会先用一个 foreach
和另一个 foreach
放在里面,就像这样!
所以我做了 2 个 MySQL 查询 $postinfo 包含帖子的所有用户信息,第二个 MySQL 查询 $comments 包含每个帖子的所有评论。
现在这行得通了,但我想知道是否有更好的方法、更好的做法?我想解决这个问题的原因是因为我想对评论进行 AJAX 以便它们可以自动更新,而且这种方式似乎很慢
<?php
foreach ($postinfo as $info) {
echo "<div id='container'>
<div id='userpost'>
<p>" . $info['firstn'] . "</p>
<p>" . $info['posttext'] . "</p>
</div>";
foreach ($comments as $comment) {
echo "<div id='comments'>
<p>' . $comment['firstn'] . '</p>
<p>' . $comment['commenttext'] . '</p>
</div>"
}
echo "</div>";
}
?>
此查询在 foreach 内部运行以获取特定帖子的评论。
$comments = regular_query(
"SELECT a.from_who, a.dateposted, a.topostid, a.commenttext, b.firstn
FROM postcomments a
INNER JOIN users b ON a.from_who = b.id
WHERE a.topostid = :postid",
["postid" => $post_idr], $conn);
这个在foreach之外:
$postinfo = regular_query(
"SELECT b.id, b.from_user, b.dateadded, b.posttype, b.posttext, b.photoname, d.firstn, d.lastn, e.status
FROM board b
INNER JOIN userprofiles c
INNER JOIN users d
INNER JOIN friendship e
ON b.from_user = c.user_id
AND b.from_user = d.id
AND e.friend_ids = b.from_user
WHERE e.status = 'Friend'
AND e.user_ids = :id
ORDER BY b.id DESC",
["id" => (int)$user_id], $conn);
最佳答案
流程一: 您可以使用一个查询来获取一篇帖子及其所有评论。但是它有一个问题例如一个帖子有 20 条评论所以它会得到帖子数据 20 次 查询:
Select post.* form post join comment on post.postId=comment.postId where post.postId='your specific post id'
[您可能需要稍微更改一下查询,或者可能有一些错字,因为我没有在表格中检查]
过程二: 有两个变量一个是 dic 另一个是数组 发布数据将在字典中,其中包含一个元素,其中包含注释数组
$postData={
postId:1,
comment:({commentId:1,comment:"bla bla bla"},
{commentId:2,comment:"bla bla bla"}),
post:"bla bla post"
}
对于帖子你必须运行
Select * from post where postId=your specific id
并征求意见
Select * from comment where postId=your specific id
就这么简单
编辑:
for(int i=0;i<postResult.count;i++)
{
if(i==0)
{
Print Your Post Info//so your post info will be echoed once
}
Print Your comment info//all your comment will be echoed here if any
}
关于php - 如何在 foreach 语句中组合 2 个单独的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23774840/