简体   繁体   中英

while else statement? PHP

So I have a validation in null values using while statement the code is

while (!$rs->EOF){ 
    echo "<tr><td>".$rs->Fields("Branch")."</td>";
    $rs->movenext();
}
$rs->Close();   

?>

What I wanted to achieve is to have an "else" statement though I know its not possible using the where statement. Which one is equivalent of it in where statement?

while (!$rs->EOF){ 
    echo "<tr><td>".$rs->Fields("Branch")."</td>";
    $rs->movenext();
}
if(!$rs->EOF)
{
    echo "<tr><td> Branch is missing</td>";
}
$rs->Close();   

?>

I tried using "if" I didn't get any errors though it didn't print what I wanted to print

While-Else does not exists in php.

You could use:

if ($rs->EOF) {
    echo "<tr><td> Branch is missing</td>";
} else {
    while (!$rs->EOF){ 
        echo "<tr><td>".$rs->Fields("Branch")."</td>";
        $rs->movenext();
    }
}
$rs->Close(); 

I would like to suggest a slightly different way to approach this, it makes a bit more sense in my head:

if (!$rs.EOF()) {
    while (!$rs.EOF()) {
        // code...
    }
}
else {
    // code...
}

I think it makes more sense to me, because you generally want your expected outcome be handled within the if block, and the other outcome(s) to be handled in the else block.

while (!$rs->EOF){ means "carry on doing this until $rs->EOF is true ". When it ends, $rs-EOF will always be true (otherwise the loop wouldn't have ended), so the conditional will never pass.

You need to do a test at some point (possibly before the while loop) to see if there are any results found. Without knowing what library you are using, it's impossible to say how to do this.

You should check that the result-set is not empty before attempting to loop through it.

Eg something like this pseudo-code:

rs = sql("SELECT ...");

if (rs.isEmpty())
    print "No data";
else
{
    while (!rs.EOF())
    {
        ...
    }
}

I think below code would help you,

<?php while (!$rs->EOF){ 

     if($rs->Fields("Branch"))
     {
      echo "<tr><td>".$rs->Fields("Branch")."</td>";
     $rs->movenext();
     }else{
      echo "<tr><td> Branch is missing</td>";
     }
}

$rs->Close();   

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM