创建排名基础系统并更新排名

时间:2013-12-09 07:44:44

标签: php mysql rank

伙计们我是新来的,也是MySQL的新手......

所以我正在尝试创建一个管理团队记录的数据库。该数据库包含一个名为team的表,其中包含一组列,如下所示:

  • TeamID
  • TeamRank
  • TeamName
  • TeamWins
  • TeamLoss
  • TeamPoints

因此,议程是根据积分对球队进行排名,得分越高。

<?php
$con = mysqli_connect("", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, "SET @rownum := 0;
  INSERT INTO team( TeamRank, TeamName)
  SELECT @rownum := @rownum + 1 AS TeamRank, TeamName 
  FROM (SELECT SUM(TeamRank)AS TeamRank , TeamName 
  FROM team
  GROUP BY TeamName 
  ORDER BY TeamRank DESC) as result
  ON DUPLICATE KEY UPDATE TeamName = VALUES(TeamName);"
);

echo "<table border='1'>
  <tr>
  <th>Rank</th>
  <th>TeamID</th>
  <th>TeamName</th>
  <th>Total Points</th>
  </tr>";

while ($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['TeamRank'] . "</td>";
  echo "<td>" . $row['TeamID'] . "</td>";
  echo "<td>" . $row['TeamName'] . "</td>";
  echo "<td>" . $row['TeamPoints'] . "</td>";
  echo "</tr>";
}

echo "</table>";

mysqli_close($con);

我收到此错误

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result

我错在哪里?如果代码有问题请指导我。

PS [编辑]:我想要做的就是将TeamName,TeamWins,TeamLoss和TeamPoints作为输入,并且随着TeamPoints的增加/减少,它应该向上/向下移动排名并显示排名表。

1 个答案:

答案 0 :(得分:1)

您正在使用 mysqli_query 进行多次查询。所以你必须使用 mysqli_multi_query

将您的代码更改为:

<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$query="SET @rownum := 0;
INSERT INTO team( TeamRank, TeamName)
SELECT @rownum := @rownum + 1 AS TeamRank, TeamName 
FROM (SELECT SUM(TeamRank)AS TeamRank , TeamName 
FROM team
GROUP BY TeamName 
ORDER BY TeamRank DESC) as result
ON DUPLICATE KEY UPDATE TeamName = VALUES(TeamName);
";

echo "<table border='1'>
<tr>
<th>Rank</th>
<th>TeamID</th>
<th>TeamName</th>
<th>Total Points</th>
</tr>";

if (mysqli_multi_query($con,$query)) {

    do {
        /* store first result set */
        if ($result = mysqli_store_result($con)) {
            while ($row = mysqli_fetch_row($result)) {
                echo "<tr>";
                echo "<td>" . $row['TeamRank'] . "</td>";  
                echo "<td>" . $row['TeamID'] . "</td>";
                echo "<td>" . $row['TeamName'] . "</td>";
                echo "<td>" . $row['TeamPoints'] . "</td>";
                echo "</tr>";
            }
            mysqli_free_result($result);
        }
    } while (mysqli_next_result($con));
}
echo "</table>";


mysqli_close($con);
?>