Login form in php and mysql with source code

 

login form in php and mysql with source code


In this article, we will learn how to create a login form using HTML, PHP, MySQL, and JQuery with source code. The form will have validation to ensure that both the username and password fields are filled out before submission. If the login is successful, the user will be redirected to a home page.


HTML


The first step in creating our login form is to write the HTML code. In this example, the form is made up of two input fields for the username and password and a submit button. The form also includes error messages to display if either of the fields is left blank or using HTML to create a error message like input tag end of the closing tags mention required and the document do the work.


<div class="container mt-5">
<div class="row py-5">
<div class="col-md-6 mx-auto">
<div class="card">
<div class="card-header bg-dark text-white text-center">
<h3>Login</h3>
</div>
<div class="card-body">
<form id="login-form">
<div class="form-group mb-3">
<label for="username" class="form-label">Username:</label>
<input type="text" class="form-control" id="username" name="username">
<span class="error-message text-danger"></span>
</div>
<div class="form-group mb-3">
<label for="password" class="form-label">Password:</label>
<input type="password" class="form-control" id="password" name="password">
<span class="error-message text-danger"></span>
</div>
<div class="mb-3 py-3">
<input type="submit" class="btn btn-dark btn-block btn-bd" value="Submit">
</div>
</form>
</div>
</div>
</div>
</div>
</div>


login form in php and mysql with source code


jQuery


Next, we will write the JQuery code that will handle the form validation and the submission of the form data. The submit event is used to intercept the form submission and prevent the default behavior and before don't forget to add the JQuery script. We then retrieve the values of the username and password fields and store them in variables.


The form validation checks if either of the fields is left blank and displays an error message if so. If both fields are filled out, the form data is sent to the server using the "$.post" method or use the Ajax call method data value are send and get. If the login is successful, the user will be redirected to a home page.


$(document).ready(function() {
  $("#login-form").submit(function(e) {
    e.preventDefault();
    var username = $("#username").val();
    var password = $("#password").val();
    var hasError = false;

    if (!username) {
      $("#username").next(".error-message").text("Username is required");
      hasError = true;
    } else {
      $("#username").next(".error-message").text("");
    }

    if (!password) {
      $("#password").next(".error-message").text("Password is required");
      hasError = true;
    } else {
      $("#password").next(".error-message").text("");
    }

    if (!hasError) {
      $.post("checklogin.php", { username: username, password: password }, function(data) {
        if (data === "success") {
          window.location.href = "home.php";
        } else {
          alert("Invalid username or password");
        }
      });
    }
  });
});


PHP


The final step is to write the PHP code that will handle the form data sent from the JQuery code. The code starts by checking if the request method is a "POST" request. If so, it retrieves the values of the username and password fields from the request data and stores them in variables.


The code then connects to the MySQL database and prepares a "SELECT" statement to retrieve the user data. The statement is executed and get the result is stored data. If there is exactly one row returned, it means that the username and password match a record in the database and the login is successful. The PHP code then echoes "success" which is received by the JQuery code and used to redirect the user to the home page. If there are no matching records or more than one, the login is not successful and an error message is displayed to the user.


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = $_POST['username'];
  $password = $_POST['password'];

  // Connect to database
  $conn = mysqli_connect('localhost', 'root', '', 'dailyaspirants');

  // Check connection
  if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
  }

  // Prepare and bind
  $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? AND password = ?");
  $stmt->bind_param("ss", $username, $password);

  // Execute statement
  $stmt->execute();


  if ($stmt->num_rows === 1) {
    echo "success";
  } else {
    echo "failed";
  }

  // Close statement and connection
  $stmt->close();
  $conn->close();


Previous Post Next Post