samedi 28 mars 2015

Display errors on the same page php

If someone can figure this out it would be so helpful. So I am trying to display the errors on the same page as my log in form. I believe the problem is the form action as is always loading that page. I have added if empty conditions and variables but not sure how to add them to the HTML.



  • The error messages have been added as variables shown in the php code

  • Currently, the form action is the problem (I think) its loading checklogin.php with a blank page

  • How can I get the error messages displaying below the form on the same page?


Thanks....


HTML:



<head>
<meta charset="UTF-8">
<title>Entry form login</title>

</head>

<body>


<div class= "wrap">
<img src="/images/logo.png" alt="Highdown logo" />
<h1>Sports day</h1>
</div>


<div class='container'>
<div class='form'>
<form id ="form" action ="checklogin.php" method="post">
<label for = "user">Username:</label>
<input type ="text" name ="username"><br>

<label for ="password">Password:</label>
<input type ="password" name ="password"><br> <span class="error"> <?php echo $error;?></span>



<input type ="submit" name ="loginbutton" id ="loginbutton" value ="Log in">
</form>
</div>
</div>


<link rel="stylesheet" type="text/css" href="styles.css">
</body>


php:



<?php
session_start();
require_once 'db/connect.php';
$error='';

if (isset($_POST['loginbutton'])){

if (empty($_POST['username']) && empty($_POST['password'])) {
$error = 'Please enter your username and password';
}


else {
// Username and password sent from the form
$username = $_POST['username'];
$password = $_POST['password'];

// Protect MySQL injection
$username= stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$encryptpass = md5($password); // Use md5 to encrypt password

$sql = "SELECT * FROM teacher WHERE Username = '$username' and Password = '$encryptpass'";

$result=mysqli_query($con, $sql);

// my_sql_num row is counting table row
$count = mysqli_num_rows($result);

//If result matched $username and $password, table row must be 1 row
if ($count==1) {
$_SESSION['Username']=$username;
header("location:homepage.php");
}

else {
$error = 'Username and/or password is invalid';
}
}
}
?>

Aucun commentaire:

Enregistrer un commentaire