I have a like button, which allows users to like posts on my site. If the user likes a post they have not liked before it will +1, if they press the same like button again it will -1. This is working on my virtual server on my laptop. However, the same code is not working on my live site. On my live site the user is able to like the same post multiple times, which is not what I want. I’m using a JQuery Ajax call to a PHP file that fires a some MySQL code.
Can anyone see anything obviously wrong with the PHP below?
include ("../con/config.php"); $postid = $_POST['postid']; $userid = $_POST['userid']; $query = $con->prepare("SELECT COUNT(*) AS CntPost FROM Likes WHERE UserID = ? AND PostID = ?"); $query->bind_param('ss',$userid,$postid); $query->execute(); $result = $query->get_result(); $fetchdata = $result->fetch_assoc(); $count = $fetchdata['CntPost']; if($count == 0){ $stmt = $con->prepare("INSERT INTO Likes(UserID,PostID) VALUES(?,?)"); $stmt->bind_param("ss", $userid, $postid); $stmt->execute(); } else { $stmt = $con->prepare("DELETE FROM Likes WHERE UserID = ? AND PostID = ?"); $stmt->bind_param("ss", $userid, $postid); $stmt->execute(); } // count numbers of likes in post $query = $con->prepare("SELECT COUNT(*) AS CntLike FROM Likes WHERE PostID = ?"); $query->bind_param('s', $postid); $query->execute(); $result = $query->get_result(); $fetchlikes = $result->fetch_assoc(); $totalLikes = $fetchlikes['CntLike']; $return_arr = array("likes"=>$totalLikes,"type"=>$count); echo json_encode($return_arr);
Advertisement
Answer
Managed to solve it. The issue was in the MySQL database column itself for the UserID. The number of chars for the column was not long enough and was truncating the UserID, which I populate using the sessionID. I amended this field in the database to allow for the length of a sessionID.