This tutorial guides you in building a secure login system using PHP, MySQL and Ajax. It enables users to log in and log out. In this, PHP manages the server-side logic, MySQL stores user data, and Ajax handles client-side requests.

PHP, MySQL, and Ajax Secure Login System Interactive Demo

Create the Database

The first step is to create a database that will store user data. We will use MySQL for this purpose. Here is an example SQL query that creates a table called tbl_users:

CREATE TABLE `tbl_users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `status` enum('Unverified','Verified','Disabled') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Unverified',
  PRIMARY KEY (`userid`),
  UNIQUE KEY `email` (`email`)

The table has five columns: userid, name, email, password, and status. The userid column serves as the primary key and auto-increments.

Create the Login Form

The next step is to create a login form that allows users to log in. Here is an example HTML form:

<form id="loginForm">
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="Your email address" required>
    <span id="emailError"></span>

    <label for="password" class="form-label">Password</label>
    <input type="password" name="password" id="password" required>
    <span id="passwordError"></span>
    <input type="button" id="loginButton" value="Login">
    <div id="loginError"></div>

This form contains two fields: email and password. On submission, Ajax sends this data to the server for processing.

Handle the Login Request

Upon receiving the login request, the server validates the data and checks for a matching record in the tbl_users table. Here is a PHP script that handles the login request:

<?php session_start();
// Verify if the request is POST and an Ajax call
    // Include the configuration file

    // Initialize response array and set Content-Type
    $response = [];
    header('Content-Type: application/json');

    // Sanitize the POST data
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

    // Perform validations
    if (empty($email) || empty($password)) {
        $response['message'] = 'Both email and password are required.';
    else {
        // Prepare, bind, and execute SQL statement
        $stmt = mysqli_prepare($conn, "SELECT * FROM tbl_users WHERE email = ? AND password = ?");
        mysqli_stmt_bind_param($stmt, "ss", $email, $password);

        // Validate credentials
        $result = mysqli_stmt_get_result($stmt);
        if (mysqli_num_rows($result) != 1) {
            $response['message'] = 'Invalid email or password.';

        // Fetch user details, and store it in session
        $userData = mysqli_fetch_assoc($result);

        // Check the status here
        if ($userData['status'] === 'Unverified') {
            $response['message'] = 'Your account is not verified.';
        } elseif ($userData['status'] === 'Disabled') {
            $response['message'] = 'Your account is disabled.';
        } elseif ($userData['status'] === 'Verified') {
            $_SESSION['userdata'] = $userData;
        } else {
            $response['message'] = 'An unknown error occurred.';

        // Close resources
    // Output the JSON response
    echo json_encode($response);

Add JavaScript

Incorporate JavaScript to handle client-side form validation and Ajax calls. The script below accomplishes this:

    document.addEventListener("DOMContentLoaded", () => {
        const loginForm = document.getElementById("loginForm");
        const emailError = document.getElementById("emailError");
        const passwordError = document.getElementById("passwordError");
        const loginError = document.getElementById("loginError");

        document.getElementById("loginButton").addEventListener("click", () => {
            if (!loginForm.checkValidity()) {
                emailError.textContent = ? "" :;
                passwordError.textContent = loginForm.password.checkValidity() ? "" : loginForm.password.validationMessage;

            const xhr = new XMLHttpRequest();
            const email = document.getElementById("email").value;
            const password = document.getElementById("password").value;

  "POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    const response = JSON.parse(xhr.responseText);
                    if (xhr.status === 200) {
                        window.location.href = "dashboard.php";
                return; // Successful login
            loginError.textContent = xhr.status === 500 ? "Something went wrong on the server. Please try again later." : response.message;

Implement Logout Functionality

The final step is to create a logout functionality that allows users to log out. Here is a PHP script that logs out the user:

// Redirect to the home page if 'logout' is set
    session_destroy(); // Destroy the session
    header('Location: ./'); // Redirect to home page

This code terminates the session and redirects the user to the login page.


This tutorial guided you through creating a login system with PHP, MySQL, and Ajax. It covered database creation, login form design, and server-side and client-side request handling. Use this knowledge to enhance your web applications effectively.

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram