Reputation: 814
I have a simple login system but instead of echoing out the error messages when they don't type their credentials correctly I want to be able to put the messages in <p></p>
or something similar. I tried using an empty array
$data = array();
and then setting a status variable whenever there is an error instead of using echo
$data["status"] = "...."
and on the html part i put in
<?php if ( isset($status) ) : ?>
<p><?= $status; ?></p>
<?php endif; ?>
But i can't seem to get it work.I also tried:
extract($data)
But again i am clearly doing something wrong.I am not sure if this is the correct way.Would using javascript or jquery be a bettor way to handle this?Anyway here is my code.
$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.
That keeps going.And here is the html part
<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 -->
Upvotes: 0
Views: 147
Reputation: 27356
$data["status"] = "...."
and on the html part i put in
<?php if ( isset($status) ) : ?>
<p><?= $status; ?></p>
<?php endif; ?>
Well as far as I can see, $status
isn't set. $data["status"]
is set.
As far as the proper method for passing error messages, as suggested in the comments; because this error is a value that is only really relevant in the current session, it makes sense to pass it in $_SESSION
. And because we like to give all values relevant titles, storing it in $_SESSION['error'];
is a perfectly legitimate way of passing the error message.
Upvotes: 1