Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xp and leveling system PHP MYSQL

Tags:

php

mysql

Ive looked at all the question that have been asked and with the answer, but i cannot seem to find a answer that suits me the best. What im trying to do is work on making a system that when a user is at a certain xp limit that go to the next level. and it shows how much xp is needed till the next xp.

So

lvl1 = 0 => lvl2 = 256 => lvl3 = 785 => lvl4 = 1656 => lvl5 = 2654

how would i go about doing that, so if xp is at certain amount show the amount and how much xp is needed for the next level.

like image 330
Dianamu Avatar asked Dec 31 '25 00:12

Dianamu


1 Answers

You can try something like this:

We have users_xp table in our db, with user_xp_id (primary key - auto increment), user_id and user_xp_amount (default value: 0) fields. When we want to update the user xp amount we should do it like:

$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

when we want to get the actual user xp amount we can get it from our db table

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;
            }
        }
    }
}

Later edit:

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;
like image 200
Mihai Matei Avatar answered Jan 01 '26 17:01

Mihai Matei