PHP - While / Else error? [closed]

∥☆過路亽.° 提交于 2019-12-02 23:19:06

问题


I have the following php code:

<?php




if (!isset($_REQUEST['search'])){

    while(($write=mysql_fetch_array($gamesearched)) != null){
    echo "Found!";
    }else{
    echo "No results";
    }

    }
?>

And it's giving me an error:

Parse error: syntax error, unexpected 'else' (T_ELSE) in C:\php\www\Gameplay\backgame.php on line 41


回答1:


In PHP, a while statement can't have an else clause. You need something external to the while that can tell you if it was executed at least once.

How about something like this?

$total = mysql_num_rows($gamesearched);
if ($total > 0) {
    while (($write=mysql_fetch_array($gamesearched)) !== false) {
        echo "Found!";
    }
} else {
    echo "No results";
}

In this case, I've looked up the total number of rows found before I start, but I could also have started by setting a counter to zero and then incrementing it inside the while loop. That would look something like this:

$total = 0;
while (($write=mysql_fetch_array($gamesearched)) !== false) {
    $total++;
    echo "Found!";
}
if ($total == 0) {
    echo "No results";
}

Note that mysql_fetch_array() returns false if there are no more rows, so I've updated the while condition for you as well.

All that being said, there are good reasons not to use mysql_* functions in new code. See this question for more details, and some better alternatives: Why shouldn't I use mysql_* functions in PHP?




回答2:


PHP doesn't support else in while statements. You will need to use a sentinel instead.




回答3:


Where is your if??? You are missing IF

Also pay attention that if/else structure is as follows: if() {} -> else {} You still misplaced else, should be outside of if statement.




回答4:


I guess you have misplaced the closing brace. See the possible correct codes below.

if (!isset($_REQUEST['search'])){
  while($write=mysql_fetch_array($gamesearched)){
    if($write != null) {
      echo "Found!";
    }else{
      echo "No results";
    }
  } 
}

or

while(($write=mysql_fetch_array($gamesearched)) != null){
  if (!isset($_REQUEST['search'])){
    echo "Found!";
  } else {
    echo "No results";
  }
}



回答5:


1)

if(xxxx){
   //do if
}else{
   //do else
}

2)

if(1):
    echo '123';
else:
    echo '456';
endif;


来源:https://stackoverflow.com/questions/17121778/php-while-else-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!