John
John

Reputation: 4944

If/else statement only working for 1 value of variable

I am using a query called $sqlStr4v that has three results, sorted by a value called totalScore2. Then I am trying to use an if/else statement to display something if a variable called $uv is included in one of the three results returned by the query.

The problem I'm having is that the if/else statement only works when $uv equals a value in the first of the three results. How can I make it work for the other two?

Thanks in advance,

John

The query:

$sqlStr4v = "SELECT 
    ...
ORDER BY totalScore2 DESC 
LIMIT 3";

The if/else statement:

$resultv = mysql_query($sqlStr4v);

while ($rowv = mysql_fetch_assoc($resultv)) {
  if ($rowv  ['username'] == $uv) {

...

}else 
{ 


...

} 

break;

Upvotes: 0

Views: 163

Answers (3)

Ishtar
Ishtar

Reputation: 11662

Why break; if you do not want to break out of the loop?

$resultv = mysql_query($sqlStr4v);

while ($rowv = mysql_fetch_assoc($resultv)) {
  if ($rowv  ['username'] == $uv) {
    echo 'something';
    //break; here if you want to display something at most once.
  }else 
  {
    echo 'nothing';
    //break; here if you want to display nothing at most once.
  }
  //break; here if you only want the first row (result is same as using LIMIT 1)
}

Upvotes: 2

Zo Has
Zo Has

Reputation: 13018

The break is causing that. You may take it out of the while loop depending on your requirement. While would execute for every database row so if break is encountered, the loop would terminate.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Instead of breaking after the first iteration as your code does, record the three values in a loop before the if statement, then test them after the loop.

Upvotes: 0

Related Questions