Derfder
Derfder

Reputation: 3324

How to make condition for this complicated loop to display value from db only for the first row?

I have a while loop for matches with rounds:

while ( $matches->fetch() ) 

{

echo $round . '.'; //need a condition to only echo round if it is for the first time
echo $team1 . ' VS ' . $team2;

}

So, instead of the result e.g.:

1.FC BARCELONA VS REAL MADRID
1.MALAGA VS SEVILLA
1.ATLETICO BILBAO VS MADRID
1.MALLORCA VS REAL MADRID
2.FC BARCELONA VS REAL MADRID
2.MALAGA VS SEVILLA
2.ATLETICO BILBAO VS MADRID
2.MALLORCA VS REAL MADRID

I need to echo the number of the round only once in the first row like that:

1.FC BARCELONA VS REAL MADRID
MALAGA VS SEVILLA
ATLETICO BILBAO VS MADRID
MALLORCA VS REAL MADRID
2.FC BARCELONA VS REAL MADRID
MALAGA VS SEVILLA
ATLETICO BILBAO VS MADRID
MALLORCA VS REAL MADRID

How to do that within while loop? I need some if or other condition, but I am out of ideas how to code this, so any help is appreciated.

I have ordered them correctly but need to do the output part now.

Upvotes: 0

Views: 102

Answers (5)

Baba
Baba

Reputation: 95121

All you need is

$last = null;
while ( $matches->fetch() ) 
{
    ($round !== $last) and print($round . '.');
    echo $team1 . ' VS ' . $team2;
    $last = $round;
}

Upvotes: 0

gregmac
gregmac

Reputation: 25291

Track the last round, and only display if it's changed.

$lastRound = null;
while ( $matches->fetch() ) 
{
    if ($lastRound != $round) 
    {
        echo $round . '.'; //need a condition to only echo round if it is for the first time
    }
    $lastRound = $round;
    echo $team1 . ' VS ' . $team2;
}

Upvotes: 2

Piepje
Piepje

Reputation: 117

Try this:

$written = false;
while ( $matches->fetch() ) {
  if(!$written) {
    echo $round . '.'; //need a condition to only echo round if it is for the first time
    $written = true;
  }
  echo $team1 . ' VS ' . $team2;
}

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

$i = 0;
while($row = $sql->fetch_assoc()) {
    if($i == 0)
        echo '1. ';
    echo $row['field'];

    $i++;
}

Upvotes: 0

Alvar FinSoft Soome
Alvar FinSoft Soome

Reputation: 740

Before while define $count = 0; inside while first thing do $count++; and secondly check

if ($count == 1) { display round number }

Upvotes: 0

Related Questions