PHP - 而/ Else错误? [英] PHP - While / Else error?

查看:146
本文介绍了PHP - 而/ Else错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下php代码:

<?php




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

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

    }
?>

它给了我一个错误:


解析错误:语法错误,
中的意外'其他'(T_ELSE)C:\ _pp\\\\Gameplay\backgame.php在第41行

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


推荐答案

在PHP中,语句不能有一个 else 子句。您需要外部的东西,而可以告诉您它是否至少执行过一次。

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.

某事怎么样这样吗?

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

在这种情况下,我查找了之前找到的总行数我开始,但我也可以通过将计数器设置为零然后在while循环内递增来开始。这看起来像这样:

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";
}

注意 mysql_fetch_array()如果没有更多行,则返回 false ,所以我也为你更新了while条件。

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

所有这一切,有充分的理由不在新代码中使用 mysql _ * 函数。有关更多详细信息和更好的替代方案,请参阅此问题:为什么不应该我在PHP中使用mysql_ *函数?

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?

这篇关于PHP - 而/ Else错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆