需要帮助才能完成此嵌套WHILE循环。
情景是
这是我的数据库中的5个表
user_info(userid,name,picurl)
user_friends(userid,friend_id)
user_post(userid,post_id,post,time)
user_likes(userid,post_id)
user_comments(userid,post_id)
我想访问user_post表并填充我的android应用程序中的数据。我可以从user_post表访问userid,post_id和time,并使用friend表中的用户的friend_id。现在要显示带有图片和名称的完整帖子,我需要访问发布者的姓名和图片来自user_info表。如果我需要显示一个1个朋友的帖子我可以做到这一点,但是当有几个朋友有超过1个帖子时,我无法得到用户的名字和picurl,并且它在json响应中显示为null。 我使用Nested While循环进行此操作以下是我的代码。
$userid = $_POST['userid'];
$query = "SELECT * FROM user_friend WHERE userid = '$userid'";
$result = mysql_query($query);
$return_arr = array();
$return_arr['newsfeed'] = array();
//Access userid
while($row = mysql_fetch_assoc($result)) {
echo "Friend Name is ".$row['friend_id']. "<br>";
$friend_id = $row['friend_id'];
$friend_id = mysql_real_escape_string($friend_id);
//accessing user_info table to access user info
$picquery = "SELECT * FROM user_info WHERE userid = '$friend_id'";
$picresult = mysql_query($picquery);
$pic = mysql_fetch_assoc($picresult);
$row_array['name'] = $pic['name'];
$row_array['picurl'] = $pic['picurl'];
$query2 = "SELECT * FROM user_post WHERE userid = '$friend_id'";
$result2 = mysql_query($query2);
//Access Posts Against userids
while( $row = mysql_fetch_array($result2) ) {
$post_id = $row['post_id'];
//for number of likes
$likesQuery = "SELECT COUNT(*) as totallikes FROM post_likes WHERE post_id = '$post_id'";
$likesResult = mysql_query($likesQuery);
$likesvalues = mysql_fetch_assoc($likesResult);
$num_of_likes = $likesvalues['totallikes'];
//for number of comments
$commentsQuery = "SELECT COUNT(*) as totalcomments FROM post_comments WHERE post_id = '$post_id'";
$commentsResult = mysql_query($commentsQuery);
$commentsvalues = mysql_fetch_assoc($commentsResult);
$num_of_comments = $commentsvalues['totalcomments'];
$row_array['post_id'] = $row['post_id'];
$row_array['userid'] = $row['userid'];
$row_array['post_text'] = $row['post_text'];
$row_array['post_time'] = $row['post_time'];
$row_array['post_num_likes'] = $num_of_likes;
$row_array['post_num_comments'] = $num_of_comments;
array_push($return_arr['newsfeed'],$row_array);
}
}
date_default_timezone_set('Asia/Karachi');
$date = date(' h:i:s a d/m/Y', time());
echo json_encode($return_arr,JSON_UNESCAPED_SLASHES);
答案 0 :(得分:1)
SELECT
p.post_id,
COUNT(c.post_id) AS comments_count,
COUNT(l.post_id) AS like_count
FROM user_post p,
user_likes l,
user_comments c
WHERE p.post_id = l.post_id
AND p.post_id = c.post
GROUP BY p.post_id