增加计数器

时间:2016-03-31 23:26:24

标签: php

我的会话检查用户是否已登录,但是当我刷新页面时,会话测试再次运行并开始执行代码,然后每次向成员在线计数器添加+1。我希望我的代码检查会话是否如下所示,但如果我刷新页面或导航到另一个页面则不会。(每次登录只有一次)这怎么可能?

PS MY代码不安全我的代码不在任何实时环境中,稍后将应用安全性以防止sql注入。

 include('..\db.php');
    $con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
    $guest_timeout = time() -1 * 60;
    $member_timeout = time() -2 * 60;
    $guest_ip = $_SERVER['REMOTE_ADDR'];
    $time = time()

    // This session check adds +1 to my member online counter when page is reloaded
    if(isset($_SESSION['CurrentUser'])){

        //if user is logged
        $sqlt = mysqli_query($con,"DELETE * FROM active_guests WHERE guest_ip='".$guest_ip."'");
        $sqlt2 = mysqli_query($con,"REPLACE INTO active_members VALUES ('".$_SESSION['CurrentUser']."','".$time."')");

    }else{

        //if user not logged
        $sqlt3 = mysqli_query($con,"REPLACE INTO active_guest (guest_ip,time_visited)VALUES ('".$guest_ip."','".$time."')");

    }
    $sqlt4 = mysqli_query($con,"DELETE * FROM  active_guest WHERE time_visited < ".$guest_timeout);
    $sqlt5 = mysqli_query($con,"DELETE * FROM  active_members WHERE time_visited < ".$member_timeout);
    $sqlt6 = mysqli_query($con,"SELECT guest_ip FROM active_guests");
    $online_guests = mysqli_num_rows($sqlt6);
    $sqlt7 = mysqli_query($con,"SELECT username FROM active_members");
    $online_members = mysqli_num_rows($sqlt7);
    ?>

    <div class="container">
    <p>online Guests : <?php echo $online_guests ; ?></p>
    <p>online Members : <?php echo $online_members ; ?></p>
    </div>

1 个答案:

答案 0 :(得分:0)

您需要username列上的唯一索引,以便REPLACE替换而不是插入重复的行。

ALTER TABLE active_members ADD UNIQUE INDEX (username);

您可能还需要guest_ip active_guests列上的唯一索引,尽管多个用户可能来自同一个IP。