I have a button that on click adds 1 to a table value in my database (i.e a like button).
When the user clicks the button:
var button_id = $(e.target).closest('div').attr('id');
var id = button_id.substring(12);
$.ajax({
method: 'POST',
url: 'update_like.php',
data: {id:id},
success: function(){
//
},
error: function(){
//
}
})
update_like.php
$id = mysqli_real_escape_string($conn,$_POST['id']);
if (!empty($_POST)){
mysqli_query($conn,"UPDATE posts SET likes=likes+1 WHERE id='$id'");
}
Q: What way can it check if they already liked it, so that they can only like the post once?
I just thought of something like this:
Have a column called "likers" or something similar, with a long list of user IDs who've liked the post.
i.e.
5 217 16 31893 ...
<-- user IDs
In update_like.php
, check if the user who's logged in's ID can be found within that string. Something like:
$id = mysqli_real_escape_string($conn,$_POST['id']);
$result = mysqli_query($conn,"SELECT likers FROM posts WHERE id='$id'");
$likers = mysqli_fetch_assoc($result);
$user_id = $_SESSION['id']; // user ID
if (!empty($_POST)){
if (!(preg_match("/\b$user_id\b/", $likers))){
mysqli_query($conn,"UPDATE posts SET likes=likes+1 WHERE id='$id'");
}
}
Is this feasible?
You can try this:
var button_id = $(e.target).closest('div').attr('id');
var id = button_id.substring(12);
var idArray = [];
if (idArray.indexOf(id) === -1) {
ajaxCall = $.ajax({
method: 'POST',
url: 'update_like.php',
data: {id:id},
success: function(){
//
idArray.push(id);
},
error: function(){
//
}
});
}
On server side you can try this: Assuming ID to be a comma separated list.
UPDATE posts
SET likes = likes+1
WHERE id = '$id'
AND FIND_IN_SET('$id', listofuserid) = 0