問題描述
我有以下 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 錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!