Breaking

Post Top Ad

Your Ad Spot

jueves, 10 de mayo de 2018

Comentarios en PHP con like y dislike

Resultado de imagen para php 

Listado de comentarios

Este código está destino a obtener la lista de comentarios y sus likes de la base de datos. Cada comentario y respuesta muestra los likes y dislikes añadidos por el usuario actual. Además, muestra también el total de likes de cada registro. El código es...
<?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
;
?>
Accederemos a estos archivos mediante jQuery AJAX. El AJAX recibirá una respuesta JSON enviada desde el código PHP y extraeremos el resultados para actualizar la UI. Las funciones de AJAX son...
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;
       
}

   
});
}

Likes y Dislike via jQuery AJAX

Al darle a Like o Dislike, se enviará una llamada AJAX al PHP para actualizar el estado de los likes en la base de datos. Para ello he creado la tabla tbl_like_unlike para almacenar los likes y dislikes de los comentarios. Los likes y dislikes se almacenarán junto al ID del correspondiente comentario al que el usuario clicó.
<?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>

No hay comentarios.:

Publicar un comentario

Post Top Ad

Your Ad Spot

Páginas