PHP - While/Else 错误?

时间:2023-04-08
本文介绍了PHP - While/Else 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有以下 php 代码:

I have the following php code:

<?php




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

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

    }
?>

它给了我一个错误:

解析错误:语法错误,意外的else"(T_ELSE) inC:phpwwwGameplayackgame.php 第 41 行

Parse error: syntax error, unexpected 'else' (T_ELSE) in C:phpwwwGameplayackgame.php on line 41

推荐答案

在 PHP 中,while 语句不能有 else 子句.你需要在 while 之外的东西,它可以告诉你它是否至少被执行过一次.

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 - While/Else 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:找出数字序列中第一个缺失的数字 下一篇:优化foreach中的while和SQL

相关文章