Reputation: 1
I have a script where members login and read posts by catagory that I have in Table called posts, then they click a button and an entry is inserted into Table called postsread collecting the postname, their memberid, and the date showing that it had been read by them. What I am looking for is a query that will display to them only the posts that they have not already read.
**Tables** **Fields** posts id, name, date, from, topic, info, cat postsread id, postname, memberid, date users id, memberid, pass, fname, lname, email
Sessions is already holding their $_SESSION['memberid'], but am unsure of how to query between the two tables to get what I'm looking for. It would be like: Show all posts in Posts except those in Postsread with the members memberid next to the corresponding postname. I am using php version 5.3, and mysql 5.0.96.
I am using the following to display posts from database:
$sql=mysql_query("SELECT * FROM posts WHERE cat='1' ORDER BY date DESC");
But this does not differentiate between if the member has clicked stating they have seen them yet or not.
I have looked many places and see examples that are close but just cant get any to fit what I am needing. I don't fully understand how to write this. I have tried many with no success. If you need extra description please ask. Thank you for your time.
Upvotes: 0
Views: 379
Reputation: 1
sql=mysql_query("SELECT * FROM posts WHERE cat='1' AND name NOT IN (SELECT postname FROM postsread WHERE memberid='$memberid') ORDER BY date DESC") or die (mysql_error());
Tadman was right on with his answer; I had something in the code that was not supposed to be there, but could not find it. Eventually I just rewrote the thing and it worked. The above worked for me, and I thank you Tadman for your help.
Upvotes: 0
Reputation: 211580
You need to construct a JOIN
condition against the posts_read
table, or use an IN
clause to exclude them. You should be very careful with your indexes as these sorts of queries can get extremely slow and database intensive with non-trivial amounts of data.
SELECT * FROM posts WHERE cat=:cat AND name NOT IN (SELECT postname FROM postsread WHERE memberid=:memberid)
Here :cat
and :memberid
are placeholders for the appropriate values. Using PDO you can bind directly to those using the execute
function.
As a note, joining on strings is a lot slower than joining on id
type values. You might want to make your postsread
table reference id
from posts
instead.
Upvotes: 1