PHP& MySQL - 循环显示结果并显示每个条目的名称和计数

时间:2012-06-22 20:23:34

标签: php mysql list loops while-loop

我正在尝试遍历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++;
} 

3 个答案:

答案 0 :(得分: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; ?>

答案 1 :(得分: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)){  

这是修复代码的方法,但您可以通过优化查询来实现此目的。

答案 2 :(得分:0)

你应该在while循环之外调用这个函数,它应该只在while循环中调用,以确保输出所有行。

mysql_fetch_assoc( $propertyGameResult);