jane
jane

Reputation: 241

Echo text only once while in if statement

I am trying to echo the weeks when a particular medal has been won .I am fetching that data from a DB , the result of which is stored in "$toprow55" .

The following is the code I am using to echo the result of the query :-

<div class="modal-body" style="white-space: pre-line ;color:black;background:#ffc266; font-size:17px ">
                <?php while( $toprow55 = sqlsrv_fetch_array( $stmt55) ){
                 if($toprow55 !== NULL){?>
              <?php  echo "Gold medals won  : "."\n". "".$toprow55['WeekNumber']."" ."\n";
                }
              else {
                {
                  echo "No  Gold medals won";
                } }}?>

                </div>

Problem :I am getting the text : "Gold medals won : " as many times as the result being echoed .I understand that I need to use " sqlsrv_fetch_array( $stmt55)" here.Please tell me how do I display "Gold medals won : " onlyonce

pic to display the current scenario :

img

Upvotes: 1

Views: 177

Answers (3)

Nordine
Nordine

Reputation: 866

It should work. You can show your label "Gold medals won" one time with a boolean set to true then to false at the end of your if condition.

<div class="modal-body" style="white-space: pre-line ;color:black;background:#ffc266; font-size:17px ">
<?php
  $i = true;
  while( $toprow55 = sqlsrv_fetch_array( $stmt55) ){
    if($toprow55 !== NULL){
       if($i) echo "Gold medals won  :\n";        
       echo $toprow55['WeekNumber']."\n";
       $i = false;
     }
  }
  if($i){
    echo "No  Gold medals won";
  } 
?>
</div>

Upvotes: 1

user7404756
user7404756

Reputation:

You need to break the while loop after the results have been achieved, otherwise while will reiterate infinity so long as $toprow55 = sqlsrv_fetch_array($stmt55) is true.

<div class="modal-body" style="white-space: pre-line ;color:black;background:#ffc266; font-size:17px ">
  <?php
    while($toprow55 = sqlsrv_fetch_array($stmt55)){
      if($toprow55 !== NULL){
        echo "Gold medals won  : "."\n". "".$toprow55['WeekNumber']."" ."\n";
      } else {
        echo "No  Gold medals won";
      };
      break;
    };
  ?>
</div>

PHP While Documentation

Upvotes: 0

Philipp
Philipp

Reputation: 15629

The simpliest way in your case would be to add an counter and ask, if the counter is zero or something else.

<?php
$i = 0;
while( $toprow55 = sqlsrv_fetch_array( $stmt55) ){
    if ($i == 0) {
        echo echo "Gold medals won  : \n";
    }

    if($toprow55 !== NULL){
        echo $toprow55['WeekNumber'] . "\n";
    } else {
        echo "No  Gold medals won";
    }
    $i++;
}
?>

Upvotes: 1

Related Questions