1

我正在尝试遍历来自 MySQL 的结果列表,并以 HTML 表格格式显示所有唯一的游戏名称和每个游戏名称的计数。它可以正常工作,直到最后一行不显示名称或计数。如果姓氏有多行,则显示名称但不显示计数。

我的代码:

$propertyGameQuery = "SELECT G.GAME_NAME FROM GAMES AS G, PROPERTY_GAMES AS PG WHERE PG.PROPERTY_ID=$cid AND G.ID=PG.GAME_ID ORDER BY G.GAME_NAME";
$propertyGameResult = mysql_query($propertyGameQuery);

$gameCount = 0;
$rowCounter = 0;
$number = mysql_num_rows($propertyGameResult);
$rws = mysql_fetch_assoc($propertyGameResult);
$starterName = $rws['GAME_NAME'];

while($propertyGames = mysql_fetch_assoc($propertyGameResult)) {
    $currentGameName = $propertyGames['GAME_NAME'];
    if(($gameCount == 0) or ($rowCounter == $number)){
    ?>
        <tr class="game-table"><td width="80%" title="<? echo $currentGameName; ?>" align="left" style="padding-left:5px;"><? echo $rowCounter ?> <? echo $currentGameName; ?></td>            
    <? 
    }
    if(($currentGameName == $starterName) or ($lastGameName == $currentGameName)){ 
        $gameCount = $gameCount + 1;    
    }else{
    ?>
        <td width="20%" align="center"><? echo $gameCount + 1; ?></td></tr>                             
    <? 
        $gameCount = 0;  
    } ?>
    <?
    $lastGameName = $currentGameName;
    $rowCounter++;
} 
4

3 回答 3

1

您可以通过查询完成所有操作

SELECT G.GAME_NAME, COUNT(*) as nb_games 
FROM GAMES G, PROPERTY_GAMES PG 
WHERE PG.PROPERTY_ID = $cid 
AND G.ID=PG.GAME_ID 
GROUP BY G.GAME_NAME
ORDER BY G.GAME_NAME

那么:

$sql = "SELECT G.GAME_NAME, COUNT(*) as nb_games"
    . " FROM GAMES G, PROPERTY_GAMES PG" 
    . " WHERE PG.PROPERTY_ID = $cid" 
    . " AND G.ID=PG.GAME_ID" 
    . " GROUP BY G.GAME_NAME"
    . " ORDER BY G.GAME_NAME";

$propertyGameResult = mysql_query($propertyGameQuery);
$counter = 0;
while(false !== ($rws = mysql_fetch_assoc($propertyGameResult)): $counter++; ?>
<tr class="game-table">
  <td width="80%" title="<?php echo $rws['GAME_NAME']; ?>" align="left" style="padding-left:5px;">  
    <?php echo $counter ?> <?php echo $rws['GAME_NAME']; ?>
  </td>
  <td width="20%" align="center">
    <?php echo $rws['nb_games']; ?>
  </td>
</tr>
<?php endwhile; ?>
于 2012-06-22T20:30:48.260 回答
1

要显示最后一行,您需要更改:

if(($gameCount == 0) or ($rowCounter == $number)){ 

if(($gameCount == 0) or ($rowCounter-1 == $number)){ 

这是因为您从 0 开始计数,并且在此调用之后才进行行计数。

您还应该更改:

if(($currentGameName == $starterName) or ($lastGameName == $currentGameName)){  

if((($currentGameName == $starterName) or ($lastGameName == $currentGameName)) && ($rowCounter-1 != $number)){  

这就是修复代码的方法,但您可以通过优化查询来做到这一点。

于 2012-06-22T20:35:04.433 回答
0

您应该在 while 循环之外调用此函数一次,它应该只在 while 循环内调用以确保输出所有行。

mysql_fetch_assoc( $propertyGameResult);
于 2012-06-22T20:30:39.800 回答