Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
I want to create a like button just like that of social media, but I don't seem to find any answer that worked fine for me, I don't know if anyone has ever come across to help out. I tried the [ON DUPLICATE KEY] AND [STORE PROCEDURE]. All only update otherwise insert, what if the user like an article [STATUS = 1] then he unlike the article [now STATUS = 0], after some few minutes he then like the article again [now STATUS = 1].
I need any sample of MySQL statement too achieve that please.

What I have tried:

INSERT INTO if_exist('id','email','status') VALUES('','myname@yahoo.com','1') ON DUPLICATE KEY UPDATE status = '0'
Posted
Updated 18-Oct-21 23:01pm

Check if exists first and if it does, do an update, otherwise do an insert.
 
Share this answer
 
Comments
CHill60 19-Oct-21 5:09am    
That is essentially what the OP's code is already doing, or trying to do.
A couple of things concern me - firstly you are using text for the status. Try changing the type of status to be an tinyint or a bit. You can then use the bitwise XOR operator ^ (caret) to "toggle" between the values on each update
SQL
INSERT INTO if_exist('id','email','status') VALUES('','myname@yahoo.com',1) ON DUPLICATE KEY UPDATE status = status ^ 1
I.e. on first insert the value of status = 1 (Liked)
On 2nd attempt status will be changed to 0 (Unliked)
On 3rd attempt status will be changed to 1 (Liked, again)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900