i was following a tutorial on youtube to make a simple Like/unlike button for my status system, i got most of it done, but it will not UPDATE my likes and not INSERT the like into the database, please help me say whats wrong, i tried so much now..
Function to get status:
function getStatus($conn) {
$sql = "SELECT * FROM status ORDER BY sid DESC";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
echo "<div class='post'>".$row['message']."<br>";
$result = mysqli_query($conn, "SELECT * FROM status_like WHERE uid=1 and sid=".$row['sid']."");
if (mysqli_num_rows($result) == 1) {
echo "<span><a href='' class='unlike' id='".$row['sid']."'>unlike</a></span>";
} else {
echo "<span><a href='' class='like' id='".$row['sid']."'>like</a></span></div>";
}
}
}
jquery code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.like').click(function(){
var sid = $(this).attr('id');
$.ajax({
url: 'test.php',
type: 'post',
async: false,
data: {
'liked': 1,
'sid': sid
},
success:function(){
}
});
});
});
</script>
and the last php code where i think the problem is:
if (isset($_POST['liked'])) {
$sid = $_POST['sid'];
$sql = "SELECT * FROM status WHERE sid=$sid";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$n = $row['likes'];
$uid = 1;
$sql2 = "UPDATE status SET likes=$n+1 WHERE sid=$sid";
$sql3 = "INSERT INTO status_like (uid, sid, username) VALUES (1, '$sid', '$uid')";
mysqli_query($conn, $sql2);
mysqli_query($conn, $sql3);
exit();
}
mysqliyou should be using parameterized queries andbind_paramto add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put$_POST,$_GETor any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.