How to update a column once per page viewed?

Asked

Viewed 36 times

0

I’m trying to create a hit counter, this code updates my column 1 time per session, but what I want is to update my column whenever the user views a new page.

if(!isset($_SESSION))session_start();

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

If I only use the query UPDATE It will update my column whenever I reload the page, and that’s not what I want. I want you to update my column whenever the user views a new page.

How do I do that?

1 answer

1


Put the name of each page in a variable, e.g.:

page1.php $nomePagina="pagina1";

page2.php $nomePagina="pagina2";

page code1.php

if(!isset($_SESSION))session_start();

    $nomePagina="pagina1";

    if(empty($_SESSION[$nomePagina])){

      ..........
      ..........


      $_SESSION[$nomePagina] = 1;

      //UPDATE

   };
  • I have a doubt, you don’t need a session_destroy? I don’t usually use the session_start(); so I wanted to know this.

  • 1

    Good grandpa! I always name the pages too.

  • @Natalie, you have to use session_start();, or it will increase the counter always. As for the session_destroy I don’t really know what he does, since I tested it in that counter code and it didn’t change anything.

  • @sam, titio, how about? https://i.stack.Imgur.com/jx7Ts.png

  • Ha... our mother! rs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.