I am trying to find a better algorithm here. In my problem, a user has 200 friends in his list. My database looks like this:
username friends
someid 2,3,4,6,7
What I did is when a new friend is added. The persons unique id is added to his list so here 2,3,4,6,7 are the ids of the users friends.
And the normal users info database looks like this
friends info
id profile image name info
2 his image his name presently
My algorithm is get the id 2 and fetch all the data from the table putting id = 2 then similarly 3,4,6 and more but if user has 200 friends, I was thinking it may cause a serious issue on server it keeps server busy because it should fetch data for 2 and again for 3.
So I was thinking for a better algorithm because if user has more friends the server have to perform MySQL (select * ) statement for 200 times if they are 200 friends this may cause a serious server issue.
I want to know if there is a simple algorithm to do or may be should I change the way how data is saved on database?
Sometimes I think to fetch and store all the data in a php variable and then save it to JavaScript variable and then using JavaScript perform the operations, because JavaScript is client side and removes server issue.
Update
Is the size of table is limited? I mean can a table consist of infinite rows?
friends_table
user id friend id
2 3
2 4
users_info table
user id image small info
3 some image //
4 // //
2 // //
As people suggested I would change the structure but how do I link friends_tabe to users info table?
$result = mysql(select * from friends_table where id = userdid);
$row = mysql_fetch_array($result);
above query gets all the ids of friends
Now I have to get the friends info using their id so I have to perform this statement
for($i=0 ;$i<count($row);$i++)
mysql(select * from users_info where id=$row[$i])
I think I should perform this statement so many times. In other words, do I have to loop this statement?
Instead of storing ids of all friends in one column create a many-to-many relationship with table that maps users to their friends.
Then you can select all friends info in one query
You can use the query like that: