我对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.当刷新时,它会计数,但不会更新表格。
谢谢!如果有什么不清楚请问我!
答案 0 :(得分:1)
理论上,如果game_id
是唯一的,您应该可以在一个查询中执行所有操作。
鉴于以下表结构,如果相关记录不存在,则下面的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;
诀窍是正确设置桌面上的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;
?>