PHP Comments System with Like Unlike

by Vincy. Last modified on July 8th, 2022.

Many social media websites like Facebook have the options to add like unlike for the posts, links, photos added by the user. Adding likes and unlikes using AJAX will give a good user experience.

It can be used effectively to filter and sort content. Sometimes, it can also be used to identify weeds out of the comments.

This comments system allows the user to add comments and to add replies to a particular comment added by some other user. Each comment and reply, it contains a thumb icon that is shown to the user to add likes for the comments and replies.

Initially, all the icons are in grey will represent that the comments and the replies have not yet been liked by the user. Once the user liked a comment by clicking the grey icon, then it turns to blue to update the status and the like count will also be updated.

The screenshot shows the output for the PHP comments system with like unlike. The liked comments are highlighted with the blue thumb icon, whereas grey thumbs are used as default.

php-comment-system-with-like-unlike

List Comments with Like Unlike Status and Count

This code is for getting the comments list and its likes from the database. Each comment and reply row shows the like, unlike added by the current user. Also, it shows the total likes count of each record. The code is,

<?php
require_once ("db.php");
$memberId = 1;

// To get likes status of the current user
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
?>
<?php

// To get Total  Likes
require_once ("db.php");

$commentId = $_POST['comment_id'];
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
    $totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>

These PHP files are accessed by jQuery AJAX script. The AJAX will receive the JSON response sent from the PHP code and parse the result to update the UI. In the PHP code, the JSON data format is prepared by using json_encode() function.

If you are looking for a detailed tutorial on JSON handling with PHP visit the linked article which will be more informative with easy examples.

The AJAX functions are,

function listComment() 
{
    $.post("comment-list.php",
        function (data) 
        {
            var data = JSON.parse(data);
    
            var comments = "";
            var replies = "";
            var item = "";
            var parent = -1;
            var results = new Array();
    
            var list = $("<ul class='outer-comment'>");
            var item = $("<li>").html(comments);

            for (var i = 0; (i < data.length); i++)
            {
                var commentId = data[i]['comment_id'];
                parent = data[i]['parent_comment_id'];
    
                var obj = getLikesUnlikes(commentId);
                
                if (parent == "0")
                {
                    if(data[i]['like_unlike'] >= 1) 
                    {
                        like_icon = "<img src='like.png'  id='unlike_" + data[i]['comment_id'] + "' class='like-unlike'  onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
                        like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
                    }
                    else
                    {
                           like_icon = "<img style='display:none;' src='like.png'  id='unlike_" + data[i]['comment_id'] + "' class='like-unlike'  onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
                        like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
                        
                    }
                
                    comments = "\
                        <div class='comment-row'>\
                            <div class='comment-info'>\
                                <span class='commet-row-label'>from</span>\
                                <span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
                                <span class='commet-row-label'>at</span> \
                                <span class='posted-at'>" + data[i]['date'] + "</span>\
                            </div>\
                            <div class='comment-text'>" + data[i]['comment'] + "</div>\
                            <div>\
                                <a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a>\
                                </div>\
                                <div class='post-action'>\ " + like_icon + " \
                                    <span id='likes_" + commentId + "'> " + totalLikes + " likes </span>\
                                </div>\
                            </div>";

                    var item = $("<li>").html(comments);
                    list.append(item);
                    var reply_list = $('<ul>');
                    item.append(reply_list);
                    listReplies(commentId, data, reply_list);
                }
            }
            $("#output").html(list);
        });
}
function getLikesUnlikes(commentId)
{
    $.ajax({
        type: 'POST',
        async: false,
        url: 'get-like-unlike.php',
        data: {comment_id: commentId},
        success: function (data)
        {
            totalLikes = data;
        }

    });
}

Like Unlike Comments via jQuery AJAX

While adding or unsetting the likes, an AJAX call is sent to the PHP to update the like status in the database. I have created tbl_like_unlike to store the comments like, unlike status.

In this table, the likes and the unlikes are stored as 1, -1  respectively. The likes, unlikes are stored with the reference of the corresponding comment_id for which the user added the likes.

<?php
require_once ("db.php");

$memberId = 1;
$commentId = $_POST['comment_id'];
$likeOrUnlike = 0;
if($_POST['like_unlike'] == 1)
{
$likeOrUnlike = $_POST['like_unlike'];
}

$sql = "SELECT * FROM tbl_like_unlike WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

if (! empty($row)) 
{
    $query = "UPDATE tbl_like_unlike SET like_unlike = " . $likeOrUnlike . " WHERE  comment_id=" . $commentId . " and member_id=" . $memberId;
} else
{
    $query = "INSERT INTO tbl_like_unlike(member_id,comment_id,like_unlike) VALUES ('" . $memberId . "','" . $commentId . "','" . $likeOrUnlike . "')";
}
mysqli_query($conn, $query);

$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
    $totalLikes = $fetchLikes['likesCount'];
}

echo $totalLikes;
?>
<script>
function likeOrDislike(comment_id,like_unlike)
{
  
    $.ajax({
        url: 'comment-like-unlike.php',
        async: false,
        type: 'post',
        data: {comment_id:comment_id,like_unlike:like_unlike},
        dataType: 'json',
        success: function (data) {
            
            $("#likes_"+comment_id).text(data + " likes");
            
            if (like_unlike == 1) { 
                $("#like_" + comment_id).css("display", "none");
                $("#unlike_" + comment_id).show();
            }

            if (like_unlike == -1) {
                $("#unlike_" + comment_id).css("display", "none");
                $("#like_" + comment_id).show();
            }
            
        },
        error: function (data) {
            alert("error : " + JSON.stringify(data));
        }
    });
}
</script>

Download

Comments to “PHP Comments System with Like Unlike”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page