I am trying to create a wall post script like facebook
In the newsfeed area it should display posts from current user and friends.
I am using three tables:
-
Users:
userid, username, fname, lname, sex, email. -
posts:
post_id, username, posted_by, title, type. -
friends:
Id, user1, user2.
When any user adds another user both will be added to the friends table.
I am using mysql view to create a temporary table to store all friends of current user with this statement:
$friends = "CREATE VIEW ".mysql_real_escape_string($_SESSION['username'])." AS
SELECT users.username "."FROM users, friends "."
WHERE ((users.username = friends.user1 OR users.username = friends.user2) AND
(users.username != '".mysql_real_escape_string($_SESSION['username'])."')) AND
(friends.user1 = '".mysql_real_escape_string($_SESSION['username'])."' OR
friends.user2 = '".mysql_real_escape_string($_SESSION['username'])."')";
mysql_query($friends) or die(mysql_error());
I am using below statement to display posts on page:
$query = "SELECT posts.*, user.fname, user.lname, user.username "."FROM
posts, users, ".mysql_real_escape_string($_SESSION['username'])." "."
WHERE
(users.username = ".mysql_real_escape_string($_SESSION['username']) ".username
AND users.username = posts.username) OR
(users.username = '".mysql_real_escape_string($_SESSION['username'])."' AND
users.username = posts.username)
ORDER BY posts.post_id DESC LIMIT 0, 11";
The problem is, it displays friends posts without any issue; but posts from the current users are repeated, once for each friend.
In other words, if I have 5 friends then each of my posts will be displayed 5 times.
Please let me know what’s wrong with this query and post me if there is any better way to do this.
You need to use the MySQL GROUP BY Aggregate:
This will group a post into 1 row based on post_id.