Php mysql while循环获取行

时间:2014-06-01 07:28:00

标签: php mysql

我想从数据库中获取Experience行,这会根据他们的经验对玩家进行升级,也就是说,等级经验÷100。

例如,如果玩家的经验是100,那么他的等级为1。 如果是200,那么他就是2级。

这是我的代码:

<?php
$con = mysqli_connect("localhost", "username", "password", "DB");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, "SELECT * FROM playerdata ORDER BY Bank DESC LIMIT 9999");

while($row = mysqli_fetch_array($result)) {

    $row['Unique_ID']; // ?
    echo "<br>";

    $xp = $row['Experience'];

    if ($xp == '1') {
        echo 'You\'re level one';
    }

    if ($xp == '2') {
        echo 'You\'re level 2';
    }
}

mysqli_close($con);
?>

我不知道如何使用while循环来处理while语句。

如何计算所有用户的等级?

1 个答案:

答案 0 :(得分:0)

如果你想根据经验计算水平,那么这样的事情可能是你问题的答案:

<?php

// This simulates your database.
$players = [
    ['Unique_ID' => 1, 'Experience' => '100'],
    ['Unique_ID' => 2, 'Experience' => '150'],
    ['Unique_ID' => 3, 'Experience' => '200'],
    ['Unique_ID' => 4, 'Experience' => '299'],
    ['Unique_ID' => 5, 'Experience' => '320'],
];

foreach ($players as $player) {

    // Basically, you want to get the level by dividing the experience by 100,
    // then rounding it down with the function floor(). No need for another loop.
    $level = floor($player['Experience'] / 100);

    echo 'Player #', $player['Unique_ID'], ' is level ', $level, "\n";

}

输出:

  

玩家#1是第1级

     

玩家#2是第1级

     

玩家#3是2级

     

玩家#4是2级

     

玩家#5是3级

现在,如果您想更新所有用户的级别,那么我会建议以下之一:

  • 使用计算所有用户级别的cron作业(使用上述方法)并更新数据库。
  • 更新用户&#39;他们的经历发生变化时的水平。
相关问题