【问题标题】:PHP - How to ELSE a While Statement? [duplicate]PHP - 如何 ELSE 语句? [复制]
【发布时间】:2013-06-11 21:35:16
【问题描述】:

嗯,我正在制作一个游戏网站,并且我有一个搜索栏,用户可以在其中键入他想要查找的游戏。我有这样的东西(这是一个测试,不需要阻塞sql注入):

<?php

if ($_REQUEST['search']){

    $searched = $_POST['searched'];
    $gamesearched = mysql_query("SELECT * from games WHERE name like '%$searched%'");

    while($write=mysql_fetch_array($gamesearched)){
    echo "Found it!" 
    }

}else{
echo "Search something";
}


?>

我不能在 while 语句中使用 else,所以我该怎么做才能显示“找不到游戏”之类的内容。

我正在尝试使用它但不起作用:P

while(($write=mysql_fetch_array($gamesearched)) != null){
echo "found";
}else{
echo "not found";
}

【问题讨论】:

    标签: php mysql if-statement while-loop


    【解决方案1】:

    正如您所注意到的,您不能在while 之后写else,因为它是一个循环,而不是像if 这样的控制结构。即使语法看起来非常相似,这也是完全不同的东西。

    解决您的问题的一种可能性是使用布尔变量:

    $found = false
    while(...){
      $found = true;
      // something more here
    }
    if(!$found){
      echo "nothig found";
    }
    

    【讨论】:

      【解决方案2】:

      为什么不在你的 while 语句周围加上 if 语句?

      if ($_REQUEST['search']){ $searched = $_POST['搜索']; $gamesearched = mysql_query("SELECT * from games WHERE name like '%$searched%'"); if(mysql_num_rows($gamesearched) > 0){ 而($write=mysql_fetch_array($gamesearched)){ 回声“找到了!” } } 别的 { 回声“未找到”; } }

      【讨论】:

      • 注意最后一个右括号 } 我添加在最后,以防你已经尝试过。此外,mysql num rows 函数将获取与您的查询匹配的结果数,并可用于任何 SELECT 查询。
      【解决方案3】:

      如果您只寻找一个项目,您可以提前打破循环

      while(..) {
        ..
        if ( found_smth ) break;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 2018-10-01
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        相关资源
        最近更新 更多