如何在带有if语句的循环后使用else语句?

时间:2019-03-22 22:14:52

标签: php

我正在尝试使用文本文件创建注册系统,并且在检查用户名是否被使用的循环之后,需要使用else语句来获得帮助。

如果我发现问题基本上已经解决,那么我通常只是想在使用if语句的循环之后查找如何使用else语句。这是代码:

while($i < count($logindata)-1) {
  if ($_POST['username'] == $user[$i]['username']) {
    set_message(" That username is taken", "danger");
  }
  $i++;
}
else {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
        file_put_contents('logininformation.txt', $_POST['username'] . "?=%&$#@[}[}+-789409289746829" . $_POST['password'] . "\n", FILE_APPEND);
        set_message("Account created!", "success");
    } else {
      set_message(" You have not put in a username and/or password","danger");
    }
}

我希望在循环之后能够有一个else语句,并且它可以正常工作。

2 个答案:

答案 0 :(得分:2)

循环不是条件,因此也没有else部分。循环在条件为真时运行是正确的,但条件不为真时,循环就结束了。

因此,要检查循环是否根本没有触发,您必须找到其他方法,例如自己写一个条件。

为了争辩,您COULD保存一个标志,然后进行评估,但是在大多数情况下,我不建议这样做

$i = 0;
$loopDidRun = false;
while ($i < 10) {
    $i++;
    $loopDidRun = true;
}

if (!$loopDidRun) {
    echo "loop did not run, therefore the 'else case', but not really";
}

答案 1 :(得分:0)

您的逻辑存在严重缺陷。

$failed=false;

if(empty($_POST['username']) || empty($_POST['password'])){
    $failed=true,
    set_message(" You have not put in a username and/or password","danger");
}else{
    while($i<count($logindata)-1){
        if($_POST['username']==$user[$i]['username']){
            $failed=true;
            set_message("That username is taken","danger");
            break;
        }
        $i++;
    }
}

if(!$failed){
    file_put_contents('logininformation.txt',$_POST['username']."?=%&$#@[[}+-789409289746829".$_POST['password']."\n",FILE_APPEND);
    set_message("Account created!","success");
}

但是我在这里所做的只是修复错误的代码。在需要过滤$POST输入以禁止任何输入,密码等输入之前,不应将其存储为纯文本格式,这不是为此创建工厂的正确方法。您应该在线找到更好,更安全的示例,并从中进行工作。

相关问题