Search code examples
phpmysqlsqlcountcounter

How to make post view count on unique user using php


I been searching on stackoverflow and I been trying a few example that I found but it's not working yet so I would be really appreciated if I can get any help or suggestion.

Basically my current goal is to update the count column only on unique user. Currently the count increase when ever a user refresh their browser so I don't think that's the best way to do count view.

I've tried something like this but the view count is still increasing when ever I refresh the page.

<?php
  require_once '../config.php';
  $id = $_GET['id'];
  if (!isset($_SESSION['recent_posts'][$id])) {
    $sql = "UPDATE song SET count = count + 1 WHERE id = $id";
    $_SESSION['recent_posts'][$id] = 1;
}

  $stmt = $conn->prepare($sql);
  $stmt->execute();
?>

Solution

  • You can do this by using cookies.

    <?php
      require_once '../config.php';
      $id = (int)$_GET['id'];
    
    
        if (!isset($_COOKIE['view_counted'])) {
            setcookie('view_counted', $id, time() + (86400 * 30), "/"); // 86400 = 1 day
            if (!isset($_SESSION['recent_posts'][$id])) {
                $sql = "UPDATE song SET count = count + 1 WHERE id = $id";
                $_SESSION['recent_posts'][$id] = 1;
            }
            $stmt = $conn->prepare($sql);
            $stmt->execute();
    
        }elseif (isset($_COOKIE['view_counted']) && $_COOKIE['view_counted'] != $id) {
            setcookie('view_counted', $id, time() + (86400 * 30), "/"); // 86400 = 1 day
            if (!isset($_SESSION['recent_posts'][$id])) {
                $sql = "UPDATE song SET count = count + 1 WHERE id = $id";
                $_SESSION['recent_posts'][$id] = 1;
            }
            $stmt = $conn->prepare($sql);
            $stmt->execute();
        }else{
            //you have already counted this as view.
        }
    
    
    ?>