[英]How do I make sure my like button is pressed only once by user?
Like Button's table 像Button的表一样
A separate post table has the POST_ID from above that is unique for each post 一个单独的post表具有上面的POST_ID,对于每个帖子都是唯一的
A separate user table exists for users 用户存在单独的用户表
So when a user clicks the like button, it adds +1 to the Like table where post_id is whatever post they are liking. 因此,当用户单击like按钮时,它会向Like表中添加+1,其中post_id是他们喜欢的任何帖子。
javascript file javascript文件
$(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 file like.php文件
$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'];
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. 我发现网络上的facebook风格就像阻止人们这样做的脚本,但它们基于IP地址(如果你没有登录就不能喜欢我的帖子)这些代码让我感到困惑,因为我不是jquery的家伙。 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. 您只需跟踪哪些用户喜欢哪些帖子以防止重复。
In the like table, remove the likes
column. 在相似的表中,删除likes
列。 We'll calculate that later. 我们稍后会计算出来。 Add a user_id
column so you can track which users like which posts. 添加user_id
列,以便跟踪哪些用户喜欢哪些帖子。 Then add a combined primary_key
on post_id
AND user_id
to prevent duplicates. 然后在post_id
和user_id
上添加组合的 primary_key
以防止重复。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.