我有一个高分表,它似乎工作正常,除了随机时间的问题似乎是将某些用户重置为0,这是我的查询:
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Main Query
$retval = mysql_query("
INSERT INTO
highscores(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = '$time',
Videos = '$videos',
Credits = '$credits'
",
$conn
);
大部分时间它都会更新,有人能看出问题所在吗?
答案 0 :(得分:2)
我想你想要更新积分而不是零。
假设您在执行查询之前将$ credit设置为0,而ON DUPLICATE KEY UPDATE部分将导致当前用户信用归零。相反,你应该做这样的事情:
<?php
$user = 109;
$time = time();
$videos = 'something';
$credits = 0;
$retval = mysql_query("INSERT INTO
highscores
(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = '$time',
Videos = '$videos',
Credits = Credits + 1", $conn);
答案 1 :(得分:1)
我认为你在寻找
$query = sprintf("INSERT INTO highscores(Username, Time, Videos, Credits)
VALUES('%s', '%s', '%s', '%s')
ON DUPLICATE KEY UPDATE Time = Time + %2$s, Videos = Videos + %3$s, Credits = Credits + %4$s"
mysql_real_escape_string($user), // escape every variable you will be using in
mysql_real_escape_string($time), // an SQL query to protect yourself against
mysql_real_escape_string($videos), // SQL injection or use parametriezed
mysql_real_escape_string($credits)); // queries with wrappers such as PDO or MySQLi
$retval = mysql_query($query,$conn);
如果用户已存在,则只会将新值添加到当前Credits
,但不会更改其他任何内容。这对我来说似乎合乎逻辑。如果您还需要增加其他列,例如Videos
,请执行与Credits
相同的操作。
答案 2 :(得分:0)
其他人指出导致此行为的原因。这是ON DUPLICATE UPDATE
// Main Query
$retval = mysql_query("
INSERT INTO highscores
(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = Time + VALUES(Time),
Videos = Videos + VALUES(Videos),
Credits = Credits + VALUES(Credits)
",
$conn
);