Site Hit

Discussion in 'PHP' started by shivam0101, Dec 22, 2009.

  1. #1
    Hello,

    session_start();
    $total_rows = mysql_num_rows(mysql_query("SELECT * FROM hits WHERE hit_session ='".session_id()."'"));

    if($total_rows == 0)
    {
    mysql_query("INSERT INTO hits SET ip='".$_SERVER[REMOTE_ADDR]'']."', hit_session='".session_id()."'");
    }


    the above code is in hits.php and it is included in all the pages. The hits are getting recorded with different session_id's but very frequenty, even if the user does not close the browser. I think even if the user navigates to another page its getting recorded in the database. Is there anything wrong in the above script?

    Thanks
     
    shivam0101, Dec 22, 2009 IP
  2. kingsoflegend

    kingsoflegend Well-Known Member

    Messages:
    202
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    108
    #2
    You need to call session_id() before session_start(). Try something like this:

    $total_rows = mysql_num_rows(mysql_query("SELECT * FROM hits WHERE hit_session ='".session_id()."'"));

    if($total_rows == 0)
    {
    mysql_query("INSERT INTO hits SET ip='".$_SERVER[REMOTE_ADDR]'']."', hit_session='".session_id()."'");
    }
    else session_start();
     
    kingsoflegend, Dec 22, 2009 IP
  3. xenon2010

    xenon2010 Peon

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    record users IP addresses instead...
     
    xenon2010, Dec 22, 2009 IP
  4. shivam0101

    shivam0101 Guest

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    For the first time session_id will be empty. So, the $total_rows will be 0 then it is inserting blank value for hit_session.
     
    shivam0101, Dec 23, 2009 IP
  5. kingsoflegend

    kingsoflegend Well-Known Member

    Messages:
    202
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    108
    #5
    Haven't thought about that... well, this makes things a lot easier.

    if (session_id()==0)
    {
    mysql_query("INSERT INTO hits SET ip='".$_SERVER[REMOTE_ADDR]'']."', hit_session='this isnt needed anymore'");
    session_start();
    }

    On the first hit, the visitor will have no session, so we record the IP and start a session. On any subsequent hits, a session will already exist, so the script won't go through the "if" anymore.
     
    kingsoflegend, Dec 23, 2009 IP
  6. shivam0101

    shivam0101 Guest

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Still not working
     
    shivam0101, Dec 29, 2009 IP