Like php mysqli

1

I'm working on a system of likes but things are very confusing, I have the Post table (The content to be tanned) with the following columns

|ID|TITLE|CONTENT|LIKES|

In the LIKES column, whenever a user presses the enjoy button, +1 is added to the current number, but I need to save every post that the user liked, this is a table to know which posts each user liked, to change the style of the button and signaling that he already liked the Post and even so he can "undo" the post. At first I thought about creating a table with the one column for the user ID and one column for each Post and set false for unkempt and true for tanned, but of course this would be impractical as there are many posts, so what is the best way to do this!

    
asked by anonymous 11.01.2018 / 18:00

1 answer

3

What you want is a relationship between NxN tables (many to many), a user can enjoy multiple posts, and a post can be enjoyed by multiple users.

The most conventional is to create a pivot table, eg:

Table name: posts_likes

+----+---------+---------+
| id | id_user | id_post |
+----+---------+---------+
|  1 |       1 |       1 | 
|  2 |       2 |       1 |  
|  3 |       1 |       2 | 
+----+---------+---------+

In this way you can check if a certain user liked a certain post:

SQL, eg:

SELECT * FROM 'posts_likes' WHERE 'id_user'= 10 AND 'id_post' = 103;

If any line is returned, this means that the user whose id = 10 liked the post whose id = 103 , and then you can change the style of the button and indicate that he already liked the Post.

    
11.01.2018 / 18:12