我有一个简单的登录系统,但是当他们没有正确输入他们的凭据时,我希望能够将消息放在<p></p>
或类似的东西中,而不是回显错误消息。我尝试使用空数组
$data = array();
然后在出现错误时设置状态变量而不是使用echo
$data["status"] = "...."
并在我放入的html部分
<?php if ( isset($status) ) : ?>
<p><?= $status; ?></p>
<?php endif; ?>
但我似乎无法让它发挥作用。我也尝试过:
extract($data)
但是我显然做错了。我不确定这是不是正确的方法。使用javascript或jquery是一种下注方式来处理这个问题吗?无论如何这里是我的代码。
$conn = DBconnect($config);
//create and empty array so we can ifor the users.
$data = array();
// if the user has submitted the form
if( $_SERVER["REQUEST_METHOD"] === "POST") {
//protect the posted value then store them to variables
$username = protect($_POST["username"]);
$password = protect($_POST["password"]);
//Check if the username or password boxes were not filled in
if ( !$username || !$password ){
// if not display an error message.
$data["status"] = "You need to fill in a username and password!";
}else{
//check if the username and password match.
$stmt = query("SELECT * FROM users WHERE username = :username AND password = :password",
array("username" => $username, "password" => $password),
$conn);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$row){
//display an error message
$data["status"] = "Username or Password is incorrect.";
}elseif($row["active"] !=1) {
$data["status"] = "You have not activated your account!";
}else{
//we log the user in.
继续前进。这里是html部分
<div class="container">
<form class="form-signin" action ="" method = "post">
<h2 class="form-signin-heading">Please Log In</h2>
<input type="text" class="input-block-level" name = "username" id = "username" placeholder="Username">
<input type="password" class="input-block-level" name = "password" id = "password" placeholder="Password">
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<input type="submit" class = "btn btn-large btn-primary" name = "submit" value="Log in!" >
<?php if ( isset($status) ) : ?>
<p><?= $status; ?></p>
<?php endif; ?>
</form>
</div> <!-- /container -->
答案 0 :(得分:1)
$data["status"] = "...."
and on the html part i put in
<?php if ( isset($status) ) : ?>
<p><?= $status; ?></p>
<?php endif; ?>
据我所知,$status
未设置。 $data["status"]
已设置。
根据评论中的建议,传递错误消息的正确方法;因为此错误是一个仅在当前会话中真正相关的值,所以在$_SESSION
中传递它是有意义的。而且因为我们希望为所有值提供相关标题,将其存储在$_SESSION['error'];
中是传递错误信息的完全合法方式。