PHP 更新 mysqli 仅在关闭浏览器之前有效

PHP update mysqli only works until closing browser

我对mysqli 中的更新功能有疑问。 对于学校,我正在尝试为我的网站创建一个点击计数器,用于计算用户访问某个页面的次数。

到目前为止我已经想到了这个:

<?php

    /*
     * ToDo: Check why number of clicks goes back to two when completely 
     * refreshing page.
     * 
     */

    include("init.php");
    session_start();

    //Count variable
    $clicks = 0;

    //Query for checking if there are any entry's in the database
    $query = "SELECT * FROM `beoordelingen`.`clickcounter` WHERE `game_id`={$id}";
    $result = $conn->query($query);

    //If query returns false
    if (!mysqli_num_rows($result)) {
        //Create entry in database
        $insert = "INSERT INTO `beoordelingen`.`clickcounter` (`ID`, `game_id`, `clicks`) VALUES (NULL, '1', '1');";
        $createEntry = $conn->query($insert);
    }

    //If query returns true
    else {

        //Setting the number of clicks equal to $clicks
        while ($data = $result->fetch_assoc()) {
            $clicks = $data['clicks'];
        }


        //Insert new number into database
        $sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
        on duplicate key update
        `clicks`=`clicks`+1;";
        $insertInto = $conn->query($sql);

        //Echo current number of clicks
        echo $clicks; 

    }

?>

实际问题是我的更新语句似乎不能正常工作。如果有人能够发现它不起作用的原因,我会很高兴。

数据库如下;

Beoordelingen <- Database
clickcounter <- Table which has the following three columns:
1. ID
2. game_id
3. clicks

脚本确实在数据库中添加了一个点击次数为 2 的条目。因此,当我重新加载页面时,它显示为 2。刷新时它会计数,但不会更新 table。

谢谢!有什么不明白的可以问我!

理论上,如果 game_id 是唯一的,您应该能够在一个查询中完成所有操作。

给定以下 table 结构,如果相关记录不存在,下面的 sql 查询将插入,如果存在则更新。


create table `clickcounter` (
    `id` int(10) unsigned not null auto_increment,
    `game_id` int(10) unsigned not null default '0',
    `clicks` int(10) unsigned not null default '0',
    primary key (`id`),
    unique index `game_id` (`game_id`)
)
engine=innodb;

诀窍是在你的 table 上正确设置 indices ~ 最初你不知道 ID 的值,我猜这是一个 auto increment primary key?因此,在 game_id 上设置一个唯一键...希望对您有所帮助!

/* Could even change `clicks`='{$clicks}' to `clicks`=1 in initial insert */
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
        on duplicate key update
        `clicks`=`clicks`+1;";



<?php
    include("init.php");
    session_start();

    /* Where / how is "$id" defined? */


    /* insert new record / update existing */
    $sql="insert into `clickcounter` set `clicks`=1, `game_id`='{$id}'
            on duplicate key update
            `clicks`=`clicks`+1;";
    $result = $conn->query( $sql );


    /* retrieve the number of clicks */
    $sql="select `clicks` from `clickcounter` where `game_id`='{$id}';";
    $result = $conn->query( $sql );

    while( $rs=$result->fetch_object() ) $clicks=intval( $rs->clicks );

    echo 'Total clicks: '.$clicks;
?>