Mardo
Mardo

Reputation: 9

Embed Php in Html

i have a code which checks if username and password match and exist in database, and i got an html document below it, which is the login form. The problem is if the user's login credentials are incorrect the statement Invalid credentials gets printed at top of the screen, I want it above the Username box in Html. Please help :)

if($username == $dbUserName && $password == $dbPassword) {
    $_SESSION['username'] = $username;
    $_SESSION['id'] = $userId;
    header('Location: user.php');
} else {
    echo "<b><i>Invalid credentials</i><b>";
}

Upvotes: 1

Views: 82

Answers (3)

user9854202
user9854202

Reputation: 1

You can put the whole thing in a function and then call it This way :

function check_credentials() {
    if($username == $dbUserName && $password == $dbPassword) {
        $_SESSION['username'] = $username;
        $_SESSION['id'] = $userId;
        header('Location: user.php');
    } else {
        echo "<b><i>Invalid credentials</i><b>";
    }
}

And you could call your function where ever you want in your form.

Upvotes: 0

Aqil
Aqil

Reputation: 114

As above mentioned,you can handle error using function,but to do it very simple and clear,define variable for the error,and put it above username input,like below :

PHP

if($username == $dbUserName && $password == $dbPassword) 
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('Location: user.php');
    }
else 
{
    $error =  "<b><i>Invalid credentials</i><b>";
}

HTML

<?php echo $error = " "; ?>
<input type="text" name="username" />

but for sure,you will need to define function for the errors,if any error occured return false,for example :

    function LoginErrors($username , $password) 
    {
    if(strlen($username) < 4 )
     {
    echo "you must choose at least 4 character for username!";
    return false;
}
    if(strlen($password) < 6)
     {
    echo "you must choose at least 6 character for password!";
return false;
     }
return true;
    }

PHP

   if($username == $dbUserName && $password == $dbPassword) 
    {
if(LoginErrors($_POST['username] , $_POST['password]) == true )
{
 $_SESSION['username'] = $username;
    $_SESSION['id'] = $userId;
    header('Location: user.php');
}
}

HTML

<?php LoginErrors(); ?>
<input type="text" name="username" />

Upvotes: 0

xanadev
xanadev

Reputation: 826

Save your error message into a variable then print it wherever you want.

your php code:

if($username == $dbUserName && $password == $dbPassword) {
    $_SESSION['username'] = $username;
    $_SESSION['id'] = $userId;
    header('Location: user.php');
} else {
    $login_error =  "<b><i>Invalid credentials</i><b>";
}

in your html part:

<div id="log_err"> <?= $login_error; ?> </div>
<input type="text" name="username">

Upvotes: 1

Related Questions