Reputation: 3111
I want to show a user the recent uploads from their friends.
I have the users friends id's in an array:
$friends
A user could have, potentially, thousands of friends.
I can select the uploads from 1 of a users friends with:
$row = $mysqli->query("SELECT * FROM photos
WHERE uploader_id = ".$friend."
ORDER BY date_uploaded
DESC LIMIT ".$page.", 25");
But I need to find all of a users friends uploads. I thought about doing this in a loop iterating over the $friends
array, but then I'd be potentially running thousands of mysql queries.
How can I do this most efficiently?
so to clarify:
search a 'photos' table for photos which are uploaded by specific users(friends), held in $friends
variable, sort by date_uploaded and limit to x results so I can have pages 1, 2, 3 etc.
Upvotes: 0
Views: 231
Reputation: 3873
Use implode to join array elements with a comma and use MySQL's IN clause.
$row = $mysqli->query("SELECT * FROM photos
WHERE uploader_id IN (". implode(',' $friends) .")
ORDER BY date_uploaded
DESC LIMIT ".$page.", 25");
Make sure your $friends
array doesn't contain any unsanitized input. As it stands right now you are open to SQL injection if $friends
is dependent on user input in any way.
Upvotes: 3