MySQL disallow row that has 2 identical column values with another row
This is my MySQL table:
- The left column auto increments.
- The center column is the id# of the user.
- The right column is the id# of a post that they like.
I am inserting data into the table like so:
$stmt = $db->prepare("INSERT INTO likes (user_id,post_id) VALUES (?,?)");
$stmt->execute(array($_SESSION['user'],$_POST['id']));
This works fine, but as you can see the MySQL table has two identical rows (id's 3 & 4) which both have a user_id of 5 and a post_id of 196. In other words my MySQL table records that the user with id = 5 likes the post with id = 196 two times. how do I disallo开发者_开发百科w a situation where there are two rows that have identical user_id's and identical post_id's
You need to set a unique constraint on the user_id and post_id columns
Update
The below answer could result in Race Conditions and possibly duplicate database entries in some cases.
Thanks to @Martin for finding the major flaws in the below system:
This is something you should do in business logic. The way I have implemented an almost identical system is this (in psuedo-code):
Show Blog/Video/Post/Etc.
Has user "liked" this?
Yes = show "unlike" button (on server, not JS)
No = show "like" button (on server, not JS)
Add or delete "like" as necessary
The code to show either button is on the server, so the user can't intercept it and manually pick which one to do.
The only flaw is that there has to be a way to identify which button the user clicks, which means the user could spend a lot of time digging and fiddling and possibly change the button/link/whatever on the page.
I overcome this by testing on the server for whether the user has already liked or not, and then inserting only when they have NOT.
CREATE UNIQUE INDEX user_post on likes (user_id, post_id)
this prevent to have same (user_id, post_id) values more than one time...
精彩评论