PHP MySQL试图加载数据

时间:2012-11-13 06:54:25

标签: php mysql database

我有一个包含游戏分数的多列表。格式是每个分数都附有一个游戏编号。然后我找到每个gameid的最高分并显示它。问题是如果游戏被删除并且游戏人数不再连续,它将显示游戏的相同高分2。一个例子是gameid 3得分5000,gameid 4得分6000,gameid 5得分3200。如果我删除gameid 4,输出将是5000-3,5000-3,3200-5。我显然不会希望它输出相同分数的2。下面是我用来执行此操作的PHP代码:

<?php

echo '<table cellpadding="0" class="content" cellspacing="0" width="100%" >';
echo '<tr><th>Game</th><th>Initials</th><th>Score</th><th>Date</th></tr>';

include("includes/sqlconnect.inc");
include("includes/functions.php");
$idnum=1;

    $allscores = mysql_query("SELECT * FROM scores");
    $highid = array(
    );
    while($row = mysql_fetch_array( $allscores ))
    {
    $idnums=$row['gameid'];
    $highid[]=$idnums;      
    }
while($idnum<=max($highid))
{
    $allscores = mysql_query("SELECT * FROM scores WHERE gameid ='$idnum'");
    $array = array(
    );
    while($row = mysql_fetch_array( $allscores ))
    {
    $score=$row['score'];
    $scoreid=$row['scoreid'];
    $array[$scoreid]=$score;      
    }
    $high=doublemax($array);
    $nameid = mysql_query("SELECT scoreid,playerid,score FROM scores WHERE scoreid='$high[i]'");
    while($row = mysql_fetch_array($nameid))
    {
    $player=$row['playerid'];
    }
    $dateid = mysql_query("SELECT scoreid,date FROM scores WHERE scoreid='$high[i]'");
    while($row = mysql_fetch_array($dateid))
    {
    if($row['date']=="")
    {
            $date="Unknown";
    }
    else
    {
            $date=$row['date'];
    }
    }
    $name = mysql_query("SELECT playerid,player_initials FROM players WHERE playerid='$player'");
    while($row = mysql_fetch_array($name))
    {
    $initials=$row['player_initials'];
    }
    $gamename = mysql_query("SELECT gameid,gamename FROM games WHERE gameid='$idnum'");
    while($row = mysql_fetch_array($gamename))
    {
    $game=$row['gamename'];
    }

    $idnum++;

            echo "<tr>";
            echo '<td>'.$game.'</td>';
            echo '<td>'.$initials.'</td>';
            echo '<td>'.number_format($score).'</td>';
            echo '<td>'.$date.'</td>';      
    echo "</tr>";

    }

echo "</table>";

?>

2 个答案:

答案 0 :(得分:1)

你做得太难了。您的查询应如下所示:

SELECT
    game_id,
    MAX(score)
FROM
    scores

然后如果你想显示关于那个游戏的更多信息而不想要重复,那么就这样做:

SELECT
    h.game_id,
    h.score,
    (
        SELECT 
            /*for example*/ date_played 
        FROM 
            scores 
        WHERE 
            game_id = h.game_id AND 
            score = h.score 
        LIMIT 1
    ) date_played
FROM
(
    SELECT
        game_id,
        MAX(score) score
    FROM
        scores
) hiscores h

简而言之:mysql是以您想要的形式获取数据的工具。不要在完全没必要的情况下过度使用php。

答案 1 :(得分:0)

问题是你是基于id的输出数而不是返回的数据行数。

而不是在以后获得最高分数,而不是在初始查询期间获得

 $allscores = mysql_query("SELECT field1, field2, MAX(score) FROM scores GROUP BY gameid"); // I don't know the field names you need obviously place those instead of field1 etc.

然后将主循环基于foreach而不是一段时间。