dongsao8279 2013-06-15 08:45
浏览 63
已采纳

PHP - 而/ Else错误? [关闭]

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

  • 写回答

5条回答 默认 最新

  • dongzi3434 2013-06-15 09:24
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?