PHP阻止数据在循环中回显两次

时间:2015-05-07 07:27:42

标签: php

考虑以下简单代码,它应该停止相同的值被回显两次

$sql = "SELECT * FROM events 
        WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby' 
        ORDER BY event_date ";

$lasttournament=""
echo'<select name="tournament" />';
 while($played>$venue){
   $tournament = $row['tournament'];

        if($tournament !== $lasttournament){
          $lasttournament = $tournament;
          echo'<option value="'.$tournament.'">'.$tournament.'</option>';           
         }//if 
      }//while

但是我的代码没有给出所需的结果,如下图所示。

enter image description here

我显然错过了一些东西,因为每场锦标赛只能展示一次

3 个答案:

答案 0 :(得分:3)

如果您只需要distinct字段,请尝试使用tournament

SELECT DISTINCT tournament FROM events 
    WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby'
    ORDER BY event_date

或尝试使用group by -

SELECT * FROM events 
    WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby'
    GROUP BY tournament 
    ORDER BY event_date

答案 1 :(得分:1)

$sql = "SELECT DISTINCT tournament FROM events 
    WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby' 
    ORDER BY event_date ";

它接缝你只需要来自sql的锦标赛,这样你就只能参加一次锦标赛。

答案 2 :(得分:1)

正如使用DISTINCT或GROUP BY将其他回复过滤值转换为sql是正确的解决方案一样,您可以使用更清晰的代码并执行更少的迭代。

无论如何,你的代码无效,因为变量$ lasttournament会在每个循环中被覆盖最后一个值,因此只有当相同的值相互连续时,你的条件才有效。