Home > Mobile >  Associative array in Login system
Associative array in Login system

Time:03-12

I have this foreach loop where it has 3 if else statement. First is it logins sucessfuly, Second is it has a wrong password and the Third one is it detects that the usernames does not exist in an array. My problem is when i try to use other username even though it is correct it detect username not indetified.

        $users = array(
        array("User" => "Joshua", "Password" => "12345"),
        array("User" => "Xen", "Password" => "x021"),
        array("User" => "Admin", "Password" => "admin"),
        array("User" => "user", "Password" => "user")
    );
    $userName =$_GET['username'];
    foreach ($users as $value) {
        if ($_GET['username'] == $value["User"] and $_GET['password'] == $value["Password"]) {
            echo "Login Succesful";
            break;
        } else if ($_GET['username'] == $value["User"] and $_GET['password'] != $value["Password"]) {
            echo "Wrong Password";
          break;
        } else {
            echo "username not identified";
            break;
        }
    }

If i try to use the username Joshua it logins successfuly, but when i try to use the Xen, Admin and User it detects "username not indentified". How can i fix the problem?

CodePudding user response:

The logic of your login is wrong because you use break in all statements that's why if the first iteration of foreach is not equal to the input then the whole foreach will be terminated. you should use the break once the login is successfull and if the password is wrong

$users = array(
    array("User" => "Joshua", "Password" => "12345"),
    array("User" => "Xen", "Password" => "x021"),
    array("User" => "Admin", "Password" => "admin"),
    array("User" => "user", "Password" => "user")
);
$userName =$_GET['username'];
$msg = "";
foreach ($users as $value) {
    if($userName == $value['User'] && $_GET['password'] == $value['Password']) 
    {
        $msg = "<p>Login successful</p>";

        //if success break the loop
        break;
    }else if ($userName == $value["User"] and $_GET['password'] != $value["Password"]) {
        $msg = "<p>Wrong Password</p>";
        //if wrong password break the loop
        break;
    }
    else
    {
       $msg = "<p>Wrong username or password</p>";
    }
}

echo $msg;
  • Related