循环数据库

时间:2016-03-15 21:34:15

标签: php loops mysqli

我想遍历我的玩家表并为每个玩家运行以下代码,我可以使用以下或使用“else”错误的选项,我需要它来运行所有的if语句来查看是否有匹配,然后根据需要更新数据库。基本上我需要知道的是我是在正确的轨道上,还是我应该看着使用do,而foreach,else,elseif,switch等等,下面的代码就是一个例子。只是想了解这个理论。

<?php
$getresult = $conn->query('SELECT id FROM users');
 while ($getrow = mysqli_fetch_array($getresult); {
    $player = $getrow['id'];

$result = $conn->query("SELECT * FROM scores WHERE player_id='$playerId' ORDER by points ASC");
$row = $result->fetch_array();
$row_count = mysqli_num_rows($result);

if ($row_count...) {


}else{

    if ($row_count...) {

    }else{

         if () {

         }else{
  }
//SQL update statement would go here..
}

1 个答案:

答案 0 :(得分:0)

您可以执行SELECT id FROM playersTable之类的操作,然后在while循环中获取player_id,然后将其余代码移到该循环中。那是你在找什么,还是我错过了什么?

// $player = $_SESSION['id'];
$playersResult = $conn->query('SELECT id FROM playersTable');
while ($playersRow = mysqli_fetch_array($playersResult); {
    $playerId = $playersRow['id'];

    $result = $conn->query("SELECT * FROM scores WHERE player_id='$playerId' ORDER by points ASC");
    $row = $result->fetch_array();
    $row_count = mysqli_num_rows($result);

    if ($row_count >= 20) { // checks that at least 10 rows available
        $result = $conn->query("SELECT points FROM scores WHERE player_id='$playerId' ORDER by points ASC LIMIT 10"); // select 10 lowest points
        while ($row = mysqli_fetch_array($result)) {
            $total = array($row['points']);
            $sum = array_sum($total);
            echo $sum;
        }
    }
    else if ($row_count>=10) { // checks that at least 10 rows available
        $result = $conn->query("SELECT points FROM scores WHERE player_id='$playerId' ORDER by points ASC LIMIT 5"); // select 5 lowest points
        while ($row = mysqli_fetch_array($result)) {
            $total = array($row['points']);
            $sum = array_sum($total);
            echo $sum;
        } 
    }

    //SQL update statement would go here..
}

您也可能想要查看总和逻辑,而不会看到您的表格结构我不认为array_sum会按照您的意愿行事。您可以使用SQL SUM()为您进行计算。