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
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?
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.
PHP doesn't support else
in while
statements. You will need to use a sentinel instead.
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";
}
}
1)
if(xxxx){
//do if
}else{
//do else
}
2)
if(1):
echo '123';
else:
echo '456';
endif;