开发者

About mysql table

I have 2 tables

usrfrnd_table

user_id friend_id
__________________
1         1

2         5

3          1

2          1

and usr_table

id fullname
________________

1  John Doe

2 George Cann
...

How to echo all friends of for example id 2 from table usr_table with loop? Tried this piece of cod开发者_如何学Goe. but doesn't work

$stmt = "SELECT fullname FROM usr_table INNER JOIN usrfrnd_table ON usr_table.id=usrfrnd_table.friend_id WHERE usrfrnd_table.user_id='$id'";
    $result=$db->query($stmt);
    foreach($result as $rec){
        echo "<li><a href=user.php?id=".$rec['id']."'>". $rec['fullname'] . "</a></li>";
    }  


Try this:

$stmt = "SELECT id, fullname FROM usr_table INNER JOIN usrfrnd_table ON usr_table.id=usrfrnd_table.friend_id WHERE usrfrnd_table.user_id=2";
$result=mysql_query($stmt);
foreach($result as $rec){
    echo $rec['fullname'] . "<br>";
} 


the query would look something like this:

select fullname from usr_table inner join usrfrnd_table ON (usr_table.id = usrfrnd_table.friend_id) WHERE usrfrnd_table.user_id = 2;


If I understand you correctly, you are wanting to show all friends of user 2. You need to do an inner join.

SELECT usr_table.fullname FROM usrfrnd_table, usr_table WHERE (usrfrnd_table.friend_id = usr_table.id) AND (usrfrnd_table.user_id = 2)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜