简体   繁体   中英

Searching for unread posts in a database

Everytime a user reads a post, it assigns a cookie, eg.

set_cookies($id,'read',60*60*24);

But the problem is how do i select all the posts that hasn't been read by the user?

SELECT * from posts where (post is unread)

It doesn't require a login. Table structure:

ID | Content | Category

With your solution, you'd do something like this:

$ids = array();
if (isset($_COOKIES)) {
    foreach ($_COOKIES as $cookie => $value) {
        if (is_numeric($cookie) && $value == 'read') {
            $ids[] = $cookie;
        }
    }
}

if (isset($ids[0])) {
    $posts = implode(',',$ids);
    $query = "SELECT * from posts where id in ({$posts})";
    // Do the query
} else {
    // no read posts.
}

But you should really look into storing your read variables differently.

I am assuming here that when user reads a post the id of the post read is stored somewhere. Let's for the moment assume that it is in the table read_posts that has a format:

UID | ID 

In this case your query becomes:

SELECT * FROM posts WHERE ID NOT IN (SELECT id FROM read_posts WHERE uid = <user's id>);

If you only allow reading sequentially and store data in the same table the query becomes even simpler:

SELECT p.* FROM posts p, read_posts rp WHERE p.ID > rp.ID AND rp.UID = <user id>;

Syntax on this query might vary slightly but the general idea I think is clear.

If you can create a list of ids that have been read, yes:

SELECT * 
FROM posts 
WHERE ID NOT IN ($list_of_post_ids_that_have_been_read)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM