1

Hi guys i'm trying to make a viewers counter which stores the value of the total viewers visited to the site. For which I'm maintaining a table called counter where i store the value of the viewers. But also I don't want to update the value of the viewers with multiple page refreshes so i drop a key into the localstorage and and during page refresh checks for that key if the key is already set, I just retrieve the value from the database while in case if the key is not present the database value will get incremented by 1.

 if(localStorage.getItem("counter")===null)
     {
        <%
            Connection con = ConnectionManager.getConnection();
            PreparedStatement ps = con.prepareStatement("Select views from counter");
            ResultSet rs = ps.executeQuery();
            long viewers=0;
            if(rs.next())
            {
                viewers = rs.getLong("views");
            }
              viewers = viewers+1;
              ps = con.prepareStatement("update counter set views = ?");
              ps.setLong(1,viewers);
              int update = ps.executeUpdate();

       %>
           var v =document.getElementById("v");
           v.innerHTML = <%= viewers %>;
           localStorage.setItem("counter",<%= viewers %>) ;
     }
     else{

           <%  
              con = ConnectionManager.getConnection();
              ps = con.prepareStatement("Select views from counter");
              rs = ps.executeQuery();
              long counts=0;
              if(rs.next())
               {
                   counts = rs.getLong("views");
               }

           %>

          var v =document.getElementById("v");
          v.innerHTML=<%= counts %>;         
     }

But I can't figure out why the value of the database is also get incremented even if the key is set in the localStorage. Also please suggest me if u have any better idea to do this.

Thanks!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
palak sharma
  • 231
  • 1
  • 12

0 Answers0