40oz
40oz

Reputation: 55

Best way to verify if a user has already like a post?

I'm making a simple like button that when a user that's logged in presses it, it adds +1 "like" to that post's "likes" column on the row with the matching id.

What I still need to do is a function, that checks if the (logged in) the user has already liked the post whenever they enter the page with the like button it, so the like button can be highlighted correctly and to avoid the same user from being able to like more than once.

My question is, whats the best way to achieve this? All I can think off is to make a column ('likedposts') in the users database that stores the ID's of the posts they've liked in a single string for example ".122354435..3453463423..3242343." with the dots separating them, and then to check if they've already liked the post therein, I'd use the LIKE parameter in mysqli for example ... WHERE 'likedposts' LIKE '%.3242343.%.

But all this just seems like lots of number crunching and so inconvenient, that it's left me wondering if there is an easier, more "compact" way to do this.
Thanks in advance, hope i explained everything well enough.

Upvotes: 0

Views: 89

Answers (1)

Quentin
Quentin

Reputation: 944118

This is a traditional many-to-many relationship.

Create a new table (e.g. user_likes) where you have a column which references the user's table as a foreign key and a column which references the posts table as a foreign key.

Depending on the database you are using, you may wish to add a third column to be the primary key, or use the two columns you already have as a composite key.

Upvotes: 2

Related Questions