Duplicate entries saved in phpmyadmin through php and javascript while we create the process of like dislike button for blogs

I want to create a like-dislike process in HTML, CSS, JavaScript, PHP, and jquery, and for that, I have a database named ows, and in this database, I have two tables named blogs and rating_info.

In the blogs table I have two rows named as follows:

blog_id,
blog_title

In the rating_info table I have three rows named as follows:

user_id,
blog_id,
rating_action

For creating this process I have made 3 files named as follows:

index.php,
server.php,
script.js,
main.css

I have hardcore user_id for testing, so I created user_id = 1.

The function which I want to make is as follows:

When user clicks on Like (thumb down) icon, the data gets saved as Like and the Like icon turns grey, when same user clicks on Dislike (thumb down) icon, the Like icon turns white, number of Like gets decreased, Dislike icon turns grey and number of Dislike gets increased.

For this, when user click on like-icon on index.php it goes to server.php for handling the queries and functions fire on script.js. In main.css, styling of the page will be done.

The error who disturbing me is that, when user click on like icon it is correctly done and that is-
like icon becomes grey, number change to zero to one and data saved successfully in the database in the form of like.
But as soon as same user click on dislike icon– like icon becomes white, dislike icon becomes grey and number of dislike change to zero to one which is correct
but number of like not change it remains same which is one. And again when I click on like icon dislike icon change to white and like icon change to grey but dislike number remain same as one and like number increases to one to two, and it is having simultaneously.

Following codes of index.php is as follows:

<?php include('server.php'); ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Like and Dislike system</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="main.css">
</head>

<body>
    <div class="blogs-wrapper">
        <?php foreach ($blogs as $blog): ?>
        <div class="blog">
            <?php echo $blog['blog_title']; ?>
            <div class="blog-info">
                <!-- if user likes blog, style button differently -->
                <i <?php if (userLiked($blog['blog_id'])): ?> class="fa fa-thumbs-up like-btn" <?php else: ?>
                    class="fa fa-thumbs-o-up like-btn" <?php endif ?> data-id="<?php echo $blog['blog_id'] ?>"></i>
                <span class="likes"><?php echo getLikes($blog['blog_id']); ?></span>

                    

                <!-- if user dislikes blog, style button differently -->
                <i <?php if (userDisliked($blog['blog_id'])): ?> class="fa fa-thumbs-down dislike-btn" <?php else: ?>
                    class="fa fa-thumbs-o-down dislike-btn" <?php endif ?> data-id="<?php echo $blog['blog_id'] ?>"></i>
                <span class="dislikes"><?php echo getDislikes($blog['blog_id']); ?></span>
            </div>
        </div>
        <?php endforeach ?>
    </div>
    <script src="scripts.js"></script>
</body>

</html>

Following are the server.php codes:

<?php 
// connect to database
$conn = mysqli_connect('localhost', 'root', '', 'ows');

// lets assume a user is logged in with id $user_id
$user_id = 1;

if (!$conn) {
  die("Error connecting to database: " . mysqli_connect_error($conn));
  exit();
}

// if user clicks like or dislike button
if (isset($_POST['action'])) {
  $blog_id = $_POST['blog_id'];
  $action = $_POST['action'];
  switch ($action) {
        case 'like':
         $sql="INSERT INTO rating_info (user_id, blog_id, rating_action) 
                   VALUES ($user_id, $blog_id, 'like') 
                   ON DUPLICATE KEY UPDATE rating_action='like'";
         break;
        case 'dislike':
          $sql="INSERT INTO rating_info (user_id, blog_id, rating_action) 
               VALUES ($user_id, $blog_id, 'dislike') 
                   ON DUPLICATE KEY UPDATE rating_action='dislike'";
         break;
        case 'unlike':
              $sql="DELETE FROM rating_info WHERE user_id=$user_id AND blog_id=$blog_id";
              break;
        case 'undislike':
          $sql="DELETE FROM rating_info WHERE user_id=$user_id AND blog_id=$blog_id";
      break;
        default:
                break;
  }

  // execute query to effect changes in the database ...
  mysqli_query($conn, $sql);
  echo getRating($blog_id);
  exit(0);
}

// Get total number of likes for a particular blog
function getLikes($id)
{
  global $conn;
  $sql = "SELECT COUNT(*) FROM rating_info 
                  WHERE blog_id = $id AND rating_action='like'";
  $rs = mysqli_query($conn, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of dislikes for a particular blog
function getDislikes($id)
{
  global $conn;
  $sql = "SELECT COUNT(*) FROM rating_info 
                  WHERE blog_id = $id AND rating_action='dislike'";
  $rs = mysqli_query($conn, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of likes and dislikes for a particular blog
function getRating($id)
{
  global $conn;
  $rating = array();
  $likes_query = "SELECT COUNT(*) FROM rating_info WHERE blog_id = $id AND rating_action='like'";
  $dislikes_query = "SELECT COUNT(*) FROM rating_info 
                                        WHERE blog_id = $id AND rating_action='dislike'";
  $likes_rs = mysqli_query($conn, $likes_query);
  $dislikes_rs = mysqli_query($conn, $dislikes_query);
  $likes = mysqli_fetch_array($likes_rs);
  $dislikes = mysqli_fetch_array($dislikes_rs);
  $rating = [
        'likes' => $likes[0],
        'dislikes' => $dislikes[0]
  ];
  return json_encode($rating);
}

// Check if user already likes blog or not
function userLiked($blog_id)
{
  global $conn;
  global $user_id;
  $sql = "SELECT * FROM rating_info WHERE user_id=$user_id 
                  AND blog_id=$blog_id AND rating_action='like'";
  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
        return true;
  }else{
        return false;
  }
}

// Check if user already dislikes blog or not
function userDisliked($blog_id)
{
  global $conn;
  global $user_id;
  $sql = "SELECT * FROM rating_info WHERE user_id=$user_id 
                  AND blog_id=$blog_id AND rating_action='dislike'";
  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
        return true;
  }else{
        return false;
  }
}

$sql = "SELECT * FROM blogs";
$result = mysqli_query($conn, $sql);
// fetch all blogs from database
// return them as an associative array called $posts
$blogs = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>

Following are the script.js:

$(document).ready(function () {
  // if the user clicks on the like button ...
  $(".like-btn").on("click", function () {
    var blog_id = $(this).data("id");
    $clicked_btn = $(this);
    if ($clicked_btn.hasClass("fa-thumbs-o-up")) {
      action = "like";
    } else if ($clicked_btn.hasClass("fa-thumbs-up")) {
      action = "unlike";
    }
    $.ajax({
      url: "index.php",
      type: "post",
      data: {
        'action': action,
        'blog_id': blog_id,
      },
      success: function (data) {
        res = JSON.parse(data);
        if (action == "like") {
          $clicked_btn.removeClass("fa-thumbs-o-up");
          $clicked_btn.addClass("fa-thumbs-up");
        } else if (action == "unlike") {
          $clicked_btn.removeClass("fa-thumbs-up");
          $clicked_btn.addClass("fa-thumbs-o-up");
        }
        // display the number of likes and dislikes
        $clicked_btn.siblings("span.likes").text(res.likes);
        $clicked_btn.siblings("span.dislikes").text(res.dislikes);

        // change button styling of the other button if user is reacting the second time to blog
        $clicked_btn
          .siblings("i.fa-thumbs-down")
          .removeClass("fa-thumbs-down")
          .addClass("fa-thumbs-o-down");
      },
    });
  });

  // if the user clicks on the dislike button ...
  $(".dislike-btn").on("click", function () {
    var blog_id = $(this).data("id");
    $clicked_btn = $(this);
    if ($clicked_btn.hasClass("fa-thumbs-o-down")) {
      action = "dislike";
    } else if ($clicked_btn.hasClass("fa-thumbs-down")) {
      action = "undislike";
    }
    $.ajax({
      url: "index.php",
      type: "post",
      data: {
        'action': action,
        'blog_id': blog_id,
      },
      success: function (data) {
        res = JSON.parse(data);
        if (action == "dislike") {
          $clicked_btn.removeClass("fa-thumbs-o-down");
          $clicked_btn.addClass("fa-thumbs-down");
        } else if (action == "undislike") {
          $clicked_btn.removeClass("fa-thumbs-down");
          $clicked_btn.addClass("fa-thumbs-o-down");
        }
        // display the number of likes and dislikes
        $clicked_btn.siblings("span.likes").text(res.likes);
        $clicked_btn.siblings("span.dislikes").text(res.dislikes);

        // change button styling of the other button if user is reacting the second time to blog
        $clicked_btn
          .siblings("i.fa-thumbs-up")
          .removeClass("fa-thumbs-up")
          .addClass("fa-thumbs-o-up");
      },
    });
  });
});

Following are the main.css:

.blogs-wrapper {
    width: 50%;
    margin: 20px auto;
    border: 1px solid #eee;
}

.blog {
    width: 90%;
    margin: 20px auto;
    padding: 10px 5px 0px 5px;
    border: 1px solid green;
}

.blog-info {
    margin: 10px auto 0px;
    padding: 5px;
}

.fa {
    font-size: 1.2em;
}

.fa-thumbs-down,
.fa-thumbs-o-down {
    transform: rotateY(180deg);
}

.logged_in_user {
    padding: 10px 30px 0px;
}

i {
    color: rgb(48, 47, 47);
}

Following are the output from the front-end when user_id=1 and when user click not click any icon:
like”0″ and dislike”0″

Following are the output from the front-end when user_id=1 and when user clicks on like icon:
like”1″ and dislike”0″

Following are the output from the front-end when user_id=1 and when user clicks on dislike icon:
like”1″ and dislike”1″

Following are the output from the front-end when user_id=1 and when user again clicks on like icon:
like”2″ and dislike”1″

Following are the current output after clicking on like and dislike icons again and again:
rating_info database

The function which I want to make is as follows:

When user clicks on Like (thumb down) icon, the data gets saved as Like and the Like icon turns grey, when same user clicks on Dislike (thumb down) icon, the Like icon turns white, number of Like gets decreased, Dislike icon turns grey and number of Dislike gets increased.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật