Gilang Rizkie Gilang Rizkie - 4 months ago 14
PHP Question

elseif not working message doesn't show

`

$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);

if (!preg_match("/^\w+$/",$username)) {
$error = true;
$username_error = "Username cant contain space and special characters";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}

$result = mysqli_query($connection, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");

if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
if ($row['id'] == 1) {
header("Location: priv8/ididthis.php");
} else if ($row['id'] >= 1) {
header("Location: index.php");
} else {
$errormsg = "Incorrect username or Password!";
}


can u see what's wrong with my code ? the
$errormsg
doesn't showing when the username or the password is wrong..

`


<body>
<div class="layout">
<div class="layout-screen">
<div class="app-title">
<h1>Login</h1>
</div>

<div class="layout-form">

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

<div class="control-group">
<input type="text" name="username" class="login-field" value="" placeholder="username" id="login-username">
<label class="login-field-icon fui-user" for="login-username"></label>
</div>

<div class="control-group">
<span><?php if (isset($username_error)) { echo $username_error; } ?></span>
</div>

<div class="control-group">
<input type="password" name="password" class="login-field" value="" placeholder="password" id="login-pass">
<label class="login-field-icon fui-lock" for="login-pass"></label>
</div>

<div class="control-group">
<span><?php if (isset($password_error)) { echo $password_error; } ?></span>
</div>

<div class="control-group">
<input class="btn btn-primary btn-large btn-block" type="submit" name="login" value="Sign in"/>
</div>

</form>

<span><?php if (isset($errormsg)) { echo $errormsg; } ?></span>

<a class="layout-link" href="forgot.php">Lost your password?</a>

</div>
</div>
</div>





Answer

The problem is that your error message is inside this block

if ($row = mysqli_fetch_array($result)){
    if ($row['id'] == 1) {...} 
    else if ($row['id'] >= 1) {...} 
    else {
        $errormsg = "Incorrect username or Password!";
    }
}

This means that the error message is never shown because row id will always be 1 or >=1. To fix, move the error message out, like this:

if ($row = mysqli_fetch_array($result)){
    if ($row['id'] == 1) {...} 
    else($row['id'] >= 1) {...}         
}
else {
    $errormsg = "Incorrect username or Password!";
}
Comments