php - MySql - three sucessfully joined tables, but failing to get one column result?
I have three tables (user, post, comments) joined up (for an ajax powered social network thing I am doing for a degree).
So far so good but when I loop through them I am getting all the results except one. The reference to who commented on a post (stored within comments table) is coming up only as a number id (which should be joined to the user table but my join is obviously not working correctly!).
Any help very much appreciated! Probably something simple as I am still new at this PHP/mysql game!
MySQL tables:
CREATE TABLE `post` (
`pid` int(10) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL,
`post` text NOT NULL,
`pid_imageurl` varchar(100) NOT NULL,
`likes` int(10) NOT NULL,
PRIMARY KEY (`pid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5
CREATE TABLE `user` (
`uid` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`uid_imageurl` varchar(100) NOT NULL,
`joindate` varchar(11) NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE `comments` (
`cid` int(10) NOT NULL AUTO_INCREMENT,
`comment_pid` int(10) NOT NULL,
`comment_uid` int(10) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Code:
$sql = "SELECT post.post, post.pid_imageurl, post.likes, user.name, comments.comment,
user.uid_imageurl, comments.comment_uid
FROM post
INNER JOIN user
ON post.uid=user.uid
LEFT JOIN comments
ON comments.comment_pid=post.pid
AND user.uid=comments.comment_uid
";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result)){?>
<ul>
<li>User Profile image here:<? echo $row['uid_imageurl']; ?></li>
<li>Post:<? echo $row['post']; ?></li>
<li>Post by:<? echo $row['name']; ?></li>
<li>Post images:<? echo $row['pid_imageurl']; ?></li>
<li>post has: <? echo $row['likes']; ?> likes.</li>
<li><? echo $row['comment']; ?></li>
<li>by: <? echo $row['comment_uid']; ?></li>
<!--This is only output as a stored id no rather than users name--!>
</ul>
<?}
?>
Answer
Solution:
First, your query should be this:
And
$row['comment_uid']
should become$row['CommentName']
.Your original query is only grabbing comments that the original poster has made (your join condition). You want to join to the
user
table yet again to get the comment poster rather than the original poster.