Embed Php in Html

◇◆丶佛笑我妖孽 提交于 2019-12-13 17:17:58

问题


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

回答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:

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



回答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

<?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" />



回答3:


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.



来源:https://stackoverflow.com/questions/50551265/embed-php-in-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!