To display error message if login fails on login form in php


I have written code for login and it redirects to deifferent pages according to user role but problem is that if there is wrong username or password it does not show error it simply shows blank page Please help me to show error meassge for wrong password or username.

loginform.php(html code)
<div id="login_form">

	&lt;form method="post" action="login.php"&gt;
		&lt;label&gt;User Name:&lt;/label&gt;
		&lt;input type="text" id="username" name="username" /&gt;
		&lt;input type="password" id="password" name="password" /&gt;
		&lt;input type="submit" id="login" value="Login" /&gt;
		&lt;input type="button" id="cancel_hide" value="Cancel" /&gt;

&lt;div id="shadow" class="popup"&gt;&lt;/div&gt;

$(document).ready(function(e) {


$("#username").change(function(e) {


    if($("#username").val().length==0 && $("#password").val().length==0)
           // $(this).next().html("Field needs filling");
		   $("#username").after('&lt;span class="errorkeyup"&gt;Field cannot be empty&lt;/span&gt;');
		   $("#password").after('&lt;span class="errorkeyup"&gt;Field cannot be empty&lt;/span&gt;');
	        //return false;
            success = false;





$username = $_REQUEST['username'];
$password = $_REQUEST['password'];

$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$login = mysql_query("select * from userlogin where username = '$username' and password = '$password'");
$num_row = mysql_num_rows($login);
if($num_row == 1) {
echo "Login Successfull";
else if($row['usertype']=='user')
else {

 // exit();
  /*echo '&lt;script type="text/javascript"&gt; 
  document.getElementById("add_err").innerHTML= "Error";




In your login.php code, you need to store the error message in a session variable - you could do something like this:

$_SESSION['errors'] = array("Your username or password was incorrect.");

Then, in your loginform.php file, add something like this above the form (or wherever you want the error to show):

<?php if (isset($_SESSION['errors'])): ?>
    <div class="form-errors">
        <?php foreach($_SESSION['errors'] as $error): ?>
            <p><?php echo $error ?></p>
        <?php endforeach; ?>
<?php endif; ?>

This will check if there are any errors set in $_SESSION and loop through and display them.


Thanks for reply I tried your code now it does not display blank page and shows login form but it does not show error message


Are you calling session_start() at the top of loginform.php?


Sorry I didn't called session_start() in loginform so code was not working for me but after adding in loginform error message is visible as soon as page is loaded it So how to solve this?