Like php mysqli

Asked

Viewed 161 times

1

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

|ID|TITLE|CONTENT|LIKES|

In the column LIKES, whenever a user presses the like button is added +1 to the current number, but I need to save every post the user likes, this is a table to know which posts each user likes, to change the style of the button and signal that he has already liked the Post and even so that he can "excuse" the post. At first I thought about creating a table with a column for the user ID and a column for each Post and setting false for not liked and true for liked, but of course this would be unfeasible because there are many posts, so what is the best way to do this!

  • I think it’s best that you create an only table of Ikes in which you register the like of each user and count the Ikes of each post from the relationship of tables, otherwise you have no way to verify which user liked or not a post.

  • Yes, but how would I do that, a table with the user id and posts he likes ? for this I should create a column for each post, or a table for each post and register each user who liked! right ?

  • I do not know if I understood it right but it is a relationship N:N between the entity USER AND POST generating a new table LIKES that should contain the foreign keys that are the key Primary of the tables USERS AND POST. You need to generate a new table in this case.

  • You create two tables and one related to these two where we have user tables and publications and a table of "Likes" that has the columns user_id and publication_id to relate the two tables, is a simple Nxn relationship

  • ah, yes I think I understand!

1 answer

3


What you want is a relationship between Nxn tables (many to many), a user can like several posts, and a post can be liked by several users.

The most conventional is to create a pivot table, e.g.:

Table name: posts_likes

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

This way you can check if a certain user likes a certain post:

SQL, ex:

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

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

  • 1

    Execelente Reply! + 1

  • @Rafaelsalomão obgado. I read the comments now, basically that’s what you said too

  • 1

    Perfect, I’ll put in practice, thank you very much!

  • Not at all @Fox, thank goodness

Browser other questions tagged

You are not signed in. Login or sign up in order to post.