如何确保用户仅按一次我的“喜欢"按钮? [英] How do I make sure my like button is pressed only once by user?
问题描述
像Button的桌子
- LIKE_ID(每个帖子的ID都一样)
- 喜欢(某人点击按钮之类的次数)
- POST_ID(对应于帖子表的POST_ID)
一个单独的帖子表具有上面的POST_ID,这对于每个帖子都是唯一的
A separate post table has the POST_ID from above that is unique for each post
为用户提供一个单独的用户表
A separate user table exists for users
因此,当用户单击喜欢"按钮时,它将+1添加到喜欢"表中,其中post_id是他们喜欢的任何帖子.
So when a user clicks the like button, it adds +1 to the Like table where post_id is whatever post they are liking.
javascript文件
javascript file
$(document).ready(function() {
$('img.like_click').click(function() {
var form = $(this).closest('form[name=like_form]');
var lid = $(form).find('input[name=lid]').val();
$.post("like.php?lid='" + lid + "', function(data) {
$(form).find('span.like_count').html(data);
});
});
like.php文件
like.php file
$lid = $_GET['lid'];
mysql_query("UPDATE tbl_likes SET likes=likes+1 WHERE like_id=".$lid) or die(mysql_error());
$result = mysql_query("SELECT likes from files where fileid=" . $id) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['likes'];
我不知道如何阻止用户一遍又一遍地喜欢.我在网站上发现类似脚本的facebook样式阻止人们执行此操作,但是它们基于IP地址(如果您未登录,您将不会喜欢我的帖子),这些代码使我感到困惑,因为我不是jQuery的家伙.我仍在尝试使用上面的代码正确显示喜欢"按钮,但是最困难的部分是限制了多个喜欢",这让我很困惑.有人可以帮忙吗?谢谢
I can't figure out how to stop a user from liking over and over. I found facebook style like scripts on the web that stop people from doing this, but they are based on IP address (you can't like my posts if you are not logged in) and those codes were confusing to me as I am not a jquery guy. I'm still trying to figure out how to show the like button properly using the above code, but the hardest part is restricting multiple likes which has stumped me. Anyone can help? Thanks
推荐答案
您说过,除非登录,否则用户不会喜欢您的帖子.因此,在您的情况下,您自己会很轻松.您只需要跟踪哪些用户喜欢哪些帖子即可防止重复.
You said that users can't like your posts unless they are logged in. So in your case, you make it very easy for yourself. You just need to track which users liked which posts to prevent duplicates.
在类似表中,删除likes
列.我们稍后再进行计算.添加user_id
列,以便您可以跟踪哪些用户喜欢哪些帖子.然后在post_id
和user_id
上添加 combined primary_key
,以防止重复.
In the like table, remove the likes
column. We'll calculate that later. Add a user_id
column so you can track which users like which posts. Then add a combined primary_key
on post_id
AND user_id
to prevent duplicates.
然后像这样构建您的查询:
Then structure your query like so:
$q = mysql_query("INSERT INTO tbl_likes (user_id, post_id) VALUES ('{$user_id}', {$post_id})");
if( $q === false ) {
// query didn't work, probably a duplicate
}
else {
// return a success etc
}
如果要获得喜欢的次数,请使用类似这样的计数查询:
And if you want to get the number of likes, use a count query like so:
SELECT post_id, count(*) as c FROM tbl_likes WHERE post_id = $post_id;
这篇关于如何确保用户仅按一次我的“喜欢"按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!