你可以尝试类似以下的方法:
我们在数据库中有一个名为
users_xp
的表,它包含
user_xp_id
(主键-自动递增)、
user_id
和
user_xp_amount
(默认值:0)字段。当我们想要更新用户的经验值时,应该这样做:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
function update_user_xp($user_id, $amount, $mysqli) {
$mysqli->query("UPDATE users_xp
SET user_xp_amount=user_xp_amount+" . $amount . "
WHERE user_id='$user_id'");
}
// we call this function like:
update_user_xp(4, 10, $mysqli); // user_id: 4, update with 10 points
当我们想要获取实际用户XP数量时,可以从我们的数据库表中获取。
function get_user_xp($user_id, $mysqli) {
$sql = $mysqli->query("SELECT user_xp_amount
FROM users_xp
WHERE user_id='$user_id'");
$row = $sql->fetch_assoc();
return $row['user_xp_amount'];
}
$xp = array('lvl1' => 0, 'lvl2' => 256, 'lvl3' => 785, 'lvl4' => 1656, 'lvl5' => 2654);
$my_xp = get_user_xp(4, $mysqli); // where 4 is my user id
for($i = 0; $i < count($xp); $i++) {
if($my_xp == $xp[$i]) {
echo 'I\'m on level ', ($i+1);
break;
}
else {
if(isset($xp[$i+1])) {
if($my_xp > $xp[$i] && $my_xp <= $xp[$i + 1]) {
echo 'My next level is ', ($i+2), ' and I need ', $xp[$i+1], ' more points for achieving it!';
break;
} else {
echo 'My next level is ', ($i+1), ' and I need ', $xp[$i], ' more points for achieving it!';
break;
}
}
}
}
后续编辑:
CREATE TABLE `my_db_name`.`users_xp` (
`user_xp_id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user_id` BIGINT NOT NULL ,
`user_xp_amount` BIGINT NOT NULL DEFAULT '0'
) ENGINE = InnoDB;