Have been trying for hours – unfortunately I’m stuck on this three-table join.
The problem is that I can retrieve all of a user’s friend’s photos. But I want the friend’s photos AND the user’s photos. However, I am unsure of the syntax for this.
Here is my table structure:
active_users: id, username, name, etc...
friends: relationship_id (PK), friend1_ID (FK), friend2_ID (FK), status
pictures: picture_id (PK), user_id (FK), name, date, etc.
So here’s the statement I currently have to get a user’s friend’s photos:
SELECT p.*, a.username
FROM friends f
JOIN active_users a ON (f.friend_1ID='$userID' AND f.friend_2ID=a.id AND status=1)
JOIN pictures p ON (p.user_id=f.friend_2ID)
How might I modify this to include the user’s photos? I can do it with a UNION, but I believe (or have been told) that this is expensive and prone to SQL attacks if there is a way in through user input.
I’ve also contemplated adding a user as a friend to himself – would this be acceptable?
You can modify the join to join on friends or the user:
Note that you should ensure $userID is escaped or, even better, use parameterised queries.