PHP SQL query issue
I have a system which is gathering all the people a user is following and also getting these peoples profile images, then displaying them on the webpage, however if a user is following 3 people, the query will loop three times for the first follower found then try and display each follower with the first followers image. Once this is has completed for each user, the query will move onto doing the same for the second follower, then each subsequent follower.
So basically the webpage looks like, [correct name and image for user 1] [correct name incorrect image for user 2] [correct name incorrect image for user 3]
[correct name incorrect image for user 1] [correct name and image for user 2] [correct name incorrect image for user 3]
and so on, depending on how many people a user is following. I feel I may not of explained this very well, if not please say and I shall rewrite
this is the code I am using
$sql_friends = "SELECT `first_name`, `surname`, `username` FROM users JOIN followers ON followers.friend_id = users.user_id WHERE followers.user_id = '$user_session_id'";
$result_friends = mysql_query($sql_friends);
while($row = mysql_fetch_array($result_friends)){
$friendforename = $row['first_name'];
$friendsurname = $row['surname'];
$friendusername = $row['username'];
$sql_img = "SELECT `img` FROM followers JOIN user_profile O开发者_C百科N followers.friend_id = user_profile.user_id WHERE followers.user_id = '$user_session_id'";
$result_img = mysql_query($sql_img);
while($img_row = mysql_fetch_assoc($result_img)){
$friend_image = $img_row['img'];
echo "<a href=\"$friendusername/\"><img src=\"../{$friendusername}/{$friend_image}\" title=\"{$friendforename} {$friendsurname}\"/></a>";
}
}
The second time you're calling mysql_query()
will mess up the results of the first one. You'll have to either specify link identifiers for them or fetch all of the results of the first query into an array first, then iterate through that one to fetch the images.
However, I think you could also do a LEFT JOIN user_profile
to get the images in the same query as the original one.
You don't need two different queries to achieve this.(I assume there can be only one record per user in user_profile table).
try the code below:
$sql_friends = "SELECT `first_name`, `surname`, `username`, `img` FROM users JOIN followers ON followers.friend_id = users.user_id LEFT JOIN user_profile ON followers.friend_id = user_profile.user_id WHERE followers.user_id = '$user_session_id'";
$result_friends = mysql_query($sql_friends);
while($row = mysql_fetch_array($result_friends)){
$friendforename = $row['first_name'];
$friendsurname = $row['surname'];
$friendusername = $row['username'];
$friend_image = $row['img'];
echo "<a href=\"$friendusername/\"><img src=\"../{$friendusername}/{$friend_image}\" title=\"{$friendforename} {$friendsurname}\"/></a>";
}
精彩评论