phpdatabasesql-updatehitcounter

How to UPDATE a column only once per ip/session?


I'm trying to make a hit counter, but this hit counter update the column counter every time the page is loaded.

$mread = $conn->prepare("UPDATE bn_publicacao SET counter = counter + 1 WHERE id = :id");
$mread->bindParam(':id', $id, PDO::PARAM_INT);
$mread->execute();

I want it to update the counter only once per ip/session. How can i do it?


Solution

  • session_start();
    

    OPTIONAL: Check if session started. Here could be a function(s) that set the session config.

    if(function_exists('session_status')){
       if(session_status() != PHP_SESSION_ACTIVE)die('no session');
    }else{
      die('no session');
    };
    

    After session has been started and configured, you can use the variables in $_SESSION.

       if(empty($_SESSION['counter']))
        {
            $_SESSION['counter'] = 1;
            $mread = $conn->prepare("UPDATE bn_publicacao SET counter = counter + 1 WHERE id = :id");
            $mread->bindParam(':id', $id, PDO::PARAM_INT);
            $mread->execute();
        };
    

    This way it will run the query code only if the $_SESSION['counter'] does not exist.

    this is only example of the counter once per session, not the query.