PHP - While / Else error?(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 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP - While/Else 错误?


- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01