Being a Rookie i am a bit lost as to how to nail this. I am trying to join three tables. This is the table structure:
Accounts Table:
1) id
2) User_id (Id given to user upon sign up)
3) Full_name
4) Username
5) Email
6) Password
Contacts Table:
1) My_id (This is the user who added friend_id)
2) Contact_id (this is the contact who was added by my_id)
3) Status (status of relationship)
Posts Table:
1) Post_id
2) User_posting (this is the user who posted it)
3) Post_name
4) User_allowed (this is where its specified who can see it)
Here is the code structure i have:
<?php
$everybody = "everybody";
$sid = "user who is logged in.";
$sql = <<<SQL
SELECT DISTINCT contacts.contact_id, accounts.full_name, posts.post_id, posts.post_name
FROM contacts, accounts, posts
WHERE
(contacts.my_id = '$sid'
AND contacts.contact_id = accounts.user_id)
OR (contacts.my_id = '$sid'
AND contacts.contact_id = accounts.user_id)
OR (posts.user_posting = '$sid'
AND contacts.contact_id = accounts.user_id
AND posts.user_allowed = '$everybody')
OR (posts.user_id = '$sid'
AND contacts.user_id = accounts.user_id
AND posts.user_allowed = '$everybody')
LIMIT $startrow, 20;
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$contactid = htmlspecialchars($row['contact_id']);
$name = htmlspecialchars($row['full_name']);
$postid = htmlspecialchars($row['post_id']);
$postname = htmlspecialchars($row['post_name']);
// If $dob is empty
if (empty($contactid)) {
$contactid = "You haven't added any friends yet.";
}
print("$contactid <br>$postname by $name <br />");
}
}
The problem is that the query shows me my posts plus all posts from friends.
What am i doing wrong?
Assuming you only want to show your friends' posts (and not your own):
$everybody = "everybody";
$sid = user who is logged in.
$sql = "SELECT a.User_id, a.Full_name, p.Post_id, p.Post_name
FROM posts p
INNER JOIN accounts a ON a.User_id = p.User_posting
INNER JOIN contacts c ON c.My_id = '$sid' AND c.Contact_id = a.User_id
WHERE p.User_allowed = '$everybody'
LIMIT $startrow, 20";
EDIT: Explaining the query.
SELECT
s certain fields used for outputFROM
the posts
table since the result should contain a row for each post.JOIN
ed with accounts
table to get the data of the posting user andJOIN
ed with contacts
table so we can filter to only have posting users that are also friends added by the user in question.$startrow
.Should be like this (Not thoroughly checked):
SELECT DISTINCT contacts.contact_id,
accounts.full_name,
posts.post_id,
posts.post_name
FROM contacts
INNER JOIN accounts ON accounts.id = contacts.id
INNER JOIN posts ON posts.User_posting = accounts.id /* (where'd get posts.user_id btw ) */
WHERE contacts.my_id = $sid
AND posts.user_allowed = $everybody
LIMIT $startrow, 20