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 cr
Solution 1:
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:
<divid="log_err"><?=$login_error; ?></div><inputtype="text"name="username">Solution 2:
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
<?phpecho$error = " "; ?><inputtype="text"name="username" />but for sure,you will need to define function for the errors,if any error occured return false,for example :
functionLoginErrors($username , $password) 
    {
    if(strlen($username) < 4 )
     {
    echo"you must choose at least 4 character for username!";
    returnfalse;
}
    if(strlen($password) < 6)
     {
    echo"you must choose at least 6 character for password!";
returnfalse;
     }
returntrue;
    }
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(); ?><inputtype="text"name="username" />Solution 3:
You can put the whole thing in a function and then call it This way :
functioncheck_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.
Post a Comment for "Embed Php In Html"