user1470755
user1470755

Reputation: 41

How do I make sure my like button is pressed only once by user?

Like Button's table

A separate post table has the POST_ID from above that is unique for each post

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.

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 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'];

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

Upvotes: 1

Views: 3741

Answers (1)

Christian
Christian

Reputation: 19740

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. 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;

Upvotes: 4

Related Questions