简体   繁体   中英

How to have an else statement after a loop with an if statement?

I am trying to make a registration system with text files and I need help with using an else statement after the loop that checks if the username is taken.

I am generally just trying to find out how to have an else statement after a loop with an if statement, if I find out that out my problem is basically solved. Here is the code:

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");
    }
}

I expect to be able to have an else statement after the loop and it working.

A loop is not a condition, therefore it does not have an else part either. It is correct that the loop runs while the condition evaluates to true, but as soon as the condition does not evaluate to true, the loop is ended.

Therefore, to check whether the loop was not triggered at all, you have to find a different way, eg write a condition on its own.

For the sake of argument, you COULD save a flag and evaluate that afterwards, but in most cases I would not recommend that :

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

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

Your logic is severely flawed.

$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");
}

However all I am doing here is fixing bad code. Before anything you need to filter the $POST input given to disallow just any input, passwords etc. should not be stored in plain text, and this is not the proper way of creating a factory for this. You should find better, and secure, examples online and work from them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM