can I make this select follower/following script more organized? (PHP/Mysql)
In this script, it gets the followers of a user and the people the user is following. Is there a better relationship/database structure to get a user's followers and who they are following? All I have right now is 2 columns to determine their relationship. I feel this is "too simple"?
(MYSQL)
USER | FRIEND
avian gary
cend gary
gary avian
mike gary
(PHP)
$followers = array();
$followings = array();
$view = $_SESSION['user']; //view is the person logged in
$query = "SELECT * FROM friends WHERE user='$view'";
$result = $db->query($query);
while($row=$result->fetch_array())
{
$follower=$row['friend'];
$followers[] = $follower;
}
print_r($followers);
echo "<br/>";
$query2 = "SELECT * FROM friends WHERE friend='$view'";
$result2 = $db->query($query2);
while($row2=$result2->fetch_array())
{
$following=$row2['user'];
$followings[] = $following;
}
print_r($followings);
echo "<br/>";
$mutual = array_inter开发者_高级运维sect($followers, $followings);
print_r($mutual);
**DISPLAY**
Your mutual friends
avian
Your followers
avian
You are following
avian
cen
mike
(I know avian is in all 3 displays, but I want to keep it that way)
If it works and it doesn't cause performance problems, keep it. 'Too simple' is never a good reason to change something that works.
You could do one query:
"SELECT * FROM friends WHERE user = '$view' OR friend = '$view';"
then
while($row = $result->fetch_array())
{
$destination = ($row['user'] == $view) ? &$followers : &$followings;
$otherUser = ($row['user'] == $view) ? $row['friend'] : $row['user'];
$destination[] = $otherUser;
}
This is less code, but its 'cleverness' makes it tougher to keep track of what's happening. Yours is easier to follow, and that counts for something.
精彩评论