Skip to main content

Basic PHP AJAX MYSQL Exam Application System.

 



An exam application is a software or web-based platform designed to facilitate the process of creating, managing, and conducting exams. These applications are commonly used by educational institutions, certification bodies, and businesses for assessments, quizzes, and tests.

Functions of an Exam Application

  1. Exam Creation & Management

    • Allows educators or administrators to design exams with various question formats (MCQs, essays, fill-in-the-blanks, etc.).
    • Supports question banks for easy reuse and randomization.
  2. Candidate Registration & Authentication

    • Manages student or candidate enrollment.
    • Provides secure logins with authentication measures to prevent cheating.
  3. Scheduling & Notifications

    • Enables scheduling of exams with specific time slots.
    • Sends automated notifications and reminders to candidates.
  4. Online Exam Execution

    • Supports different types of exams (objective, subjective, practical).
    • Offers time management features like countdown timers.
    • Can include AI proctoring, webcam monitoring, and screen recording to prevent cheating.
  5. Result Processing & Analysis

    • Automatically evaluates objective questions and generates scores.
    • Provides detailed analytics on candidate performance.
    • Allows manual grading for subjective questions.
  6. Security & Anti-Cheating Measures

    • Implements browser lockdown, IP tracking, and webcam monitoring.
    • Uses AI-powered behavior analysis to detect suspicious activity.
  7. Reporting & Certification

    • Generates detailed reports and analytics for administrators.
    • Issues digital certificates for successful candidates.
  8. Integration & Customization

    • Can integrate with Learning Management Systems (LMS) or HR software.
    • Customizable themes and settings to suit institutional needs.










To create a fully functional basic exam application with user authentication, you need to include  the essential features such as:

1. User Roles (Admin and Student)
2. Admin Panel to manage questions and users
3. Exam Timer
4. Result History
5. Validation and Security
6. Responsive Design
7. Logout Functionality

Below is the complete implementation with all required features:

sql  database :

CREATE DATABASE exam_app;


USE exam_app;


 Users Table

CREATE TABLE users (

    id INT AUTO_INCREMENT PRIMARY KEY,

    username VARCHAR(50) NOT NULL UNIQUE,

    password VARCHAR(255) NOT NULL,

    role ENUM('admin', 'student') DEFAULT 'student',

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);


 Questions Table

CREATE TABLE questions (

    id INT AUTO_INCREMENT PRIMARY KEY,

    question_text TEXT NOT NULL,

    option1 VARCHAR(255) NOT NULL,

    option2 VARCHAR(255) NOT NULL,

    option3 VARCHAR(255) NOT NULL,

    option4 VARCHAR(255) NOT NULL,

    correct_option INT NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);


 Results Table

CREATE TABLE results (

    id INT AUTO_INCREMENT PRIMARY KEY,

    user_id INT NOT NULL,

    score INT NOT NULL,

    total_questions INT NOT NULL,

    submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id)

);

db. php

<?php

// Database configuration

$host = 'localhost'; // Database host

$dbname = 'exam_app'; // Database name

$username = 'root'; // Database username

$password = ''; // Database password


try {

    // Create a PDO instance (database connection)

    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);


    // Set PDO to throw exceptions on errors

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    // Set default fetch mode to associative array

    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);


} catch (PDOException $e) {

    // Handle connection errors

    die("Database connection failed: " . $e->getMessage());

}

?>


index. php:


<?php

session_start();


// Check if the user is already logged in

if (isset($_SESSION['user_id'])) {

    header("Location: dashboard.php");

    exit;

}

?>


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Welcome to Exam Application</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            text-align: center;

            margin-top: 50px;



        }


        body{

            background:url('images/background-exam.jpg');

            background-repeat: no-repeat;

            background-size: cover;

            background-position:center;

        }



        .container {

            max-width: 600px;

            margin: 0 auto;

            padding: 20px;

            border: 1px solid #ccc;

            border-radius: 10px;

            background-color: #f9f9f9;

        }

        h1 {

            color: #333;

        }

        a {

            display: inline-block;

            margin: 10px;

            padding: 10px 20px;

            color: #fff;

            background-color: #007bff;

            text-decoration: none;

            border-radius: 5px;

        }

        a:hover {

            background-color: #0056b3;

        }

    </style>

</head>

<body>

    <div class="container">

        <h1>Welcome to the Exam Application</h1>

        <p>Please login or register to continue.</p>

        <a href="login.php">Login</a>

        <a href="register.php">Register</a>

    </div>

</body>

</html>

register. php:


<?php

session_start();

require 'db.php';


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $username = $_POST['username'];

    $password = password_hash($_POST['password'], PASSWORD_BCRYPT);


    $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");

    if ($stmt->execute([$username, $password])) {

        $_SESSION['message'] = "Registration successful! Please login.";

        header("Location: login.php");

    } else {

        $_SESSION['error'] = "Registration failed!";

    }

}

?>


<form method="POST" action="">

    <input type="text" name="username" placeholder="Username" required>

    <input type="password" name="password" placeholder="Password" required>

    <button type="submit">Register</button>

</form>

<a href="login.php">Already have an account? Login</a>

login. php:



<?php

session_start();

require 'db.php';


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $username = $_POST['username'];

    $password = $_POST['password'];


    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");

    $stmt->execute([$username]);

    $user = $stmt->fetch();


    if ($user && password_verify($password, $user['password'])) {

        $_SESSION['user_id'] = $user['id'];

        $_SESSION['role'] = $user['role'];

         $_SESSION['username'] = $user['username'];

        header("Location: dashboard.php");

    } else {

        $_SESSION['error'] = "Invalid credentials!";

    }

}

?>


<form method="POST" action="">

    <input type="text" name="username" placeholder="Username" required>

    <input type="password" name="password" placeholder="Password" required>

    <button type="submit">Login</button>

</form>

<a href="register.php">Don't have an account? Register</a>



dashboard. php:

<?php

session_start();

require 'db.php';


if (!isset($_SESSION['user_id'])) {

    header("Location: login.php");

    exit;

}


$role = $_SESSION['role'];

?>


<h1>Welcome, <?= $_SESSION['username'] ?></h1>

<?php if ($role === 'admin'): ?>

    <a href="add_question.php">Add Question</a><br>

    <a href="view_questions.php">View Questions</a><br>

<?php else: ?>

    <a href="exam.php">Take Exam</a><br>

    <a href="results.php">View Results</a><br>

<?php endif; ?>

<a href="logout.php">Logout</a>


add_question.php:

<?php

session_start();

require 'db.php';


if ($_SESSION['role'] !== 'admin') {

    header("Location: dashboard.php");

    exit;

}


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $question_text = $_POST['question_text'];

    $option1 = $_POST['option1'];

    $option2 = $_POST['option2'];

    $option3 = $_POST['option3'];

    $option4 = $_POST['option4'];

    $correct_option = $_POST['correct_option'];


    $stmt = $pdo->prepare("INSERT INTO questions (question_text, option1, option2, option3, option4, correct_option) VALUES (?, ?, ?, ?, ?, ?)");

    if ($stmt->execute([$question_text, $option1, $option2, $option3, $option4, $correct_option])) {

        $_SESSION['message'] = "Question added successfully!";

    } else {

        $_SESSION['error'] = "Failed to add question!";

    }

}

?>


<form method="POST" action="">

    <textarea name="question_text" placeholder="Question" required></textarea><br>

    <input type="text" name="option1" placeholder="Option 1" required><br>

    <input type="text" name="option2" placeholder="Option 2" required><br>

    <input type="text" name="option3" placeholder="Option 3" required><br>

    <input type="text" name="option4" placeholder="Option 4" required><br>

    <select name="correct_option" required>

        <option value="1">Option 1</option>

        <option value="2">Option 2</option>

        <option value="3">Option 3</option>

        <option value="4">Option 4</option>

    </select><br>

    <button type="submit">Add Question</button>

</form>

<a href="dashboard.php">Back to Dashboard</a>

exam. php:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Exam</title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

    <div id="questions"></div>

    <div id="timer">Time Left: 10:00</div>

    <button id="submit">Submit Exam</button>


    <script>

        let timeLeft = 600; // 10 minutes in seconds


        $(document).ready(function() {

            // Fetch questions

            $.ajax({

                url: 'fetch_questions.php',

                method: 'GET',

                success: function(data) {

                    var questions = JSON.parse(data);

                    var html = '';

                    questions.forEach(function(question, index) {

                        html += `<div>

                            <p>${question.question_text}</p>

                            <input type="radio" name="q${question.id}" value="1"> ${question.option1}<br>

                            <input type="radio" name="q${question.id}" value="2"> ${question.option2}<br>

                            <input type="radio" name="q${question.id}" value="3"> ${question.option3}<br>

                            <input type="radio" name="q${question.id}" value="4"> ${question.option4}<br>

                        </div>`;

                    });

                    $('#questions').html(html);

                }

            });


            // Timer

            setInterval(() => {

                timeLeft--;

                let minutes = Math.floor(timeLeft / 60);

                let seconds = timeLeft % 60;

                $('#timer').text(`Time Left: ${minutes}:${seconds.toString().padStart(2, '0')}`);

                if (timeLeft <= 0) {

                    alert('Time is up!');

                    submitExam();

                }

            }, 1000);


            // Submit exam

            $('#submit').click(function() {

                submitExam();

            });


            function submitExam() {

                var answers = [];

                $('input[type="radio"]:checked').each(function() {

                    answers.push({

                        questionId: $(this).attr('name').substring(1),

                        answer: $(this).val()

                    });

                });


                $.ajax({

                    url: 'submit_exam.php',

                    method: 'POST',

                    data: { answers: JSON.stringify(answers) },

                    success: function(response) {

                        alert('Exam submitted! Your score: ' + response);

                        window.location.href = 'dashboard.php';

                    }

                });

            }

        });

    </script>

</body>

</html>

fetch_questions.php:

<?php

session_start();

require 'db.php';


$stmt = $pdo->query("SELECT * FROM questions");

$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);


echo json_encode($questions);

logout. php:

<?php

session_start();

session_destroy();

header("Location: login.php");

exit;

? >

results. php:

<?php

session_start();

require 'db.php';


$stmt = $pdo->prepare("SELECT * FROM results WHERE user_id = ?");

$stmt->execute([$_SESSION['user_id']]);

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>


<table border="1">

    <tr>

        <th>ID</th>

        <th>Score</th>

        <th>Total Questions</th>

        <th>Submitted At</th>

    </tr>

    <?php foreach ($results as $result): ?>

    <tr>

        <td><?= $result['id'] ?></td>

        <td><?= $result['score'] ?></td>

        <td><?= $result['total_questions'] ?></td>

        <td><?= $result['submitted_at'] ?></td>

    </tr>

    <?php endforeach; ?>

</table>

<a href="dashboard.php">Back to Dashboard</a>

submit_exam.php:

<?php

session_start();

require 'db.php';


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $answers = json_decode($_POST['answers'], true);


    $score = 0;

    $totalQuestions = 0;


    foreach ($answers as $answer) {

        $stmt = $pdo->prepare("SELECT correct_option FROM questions WHERE id = ?");

        $stmt->execute([$answer['questionId']]);

        $correctOption = $stmt->fetchColumn();


        if ($correctOption == $answer['answer']) {

            $score++;

        }

        $totalQuestions++;

    }


    // Save result

    $stmt = $pdo->prepare("INSERT INTO results (user_id, score, total_questions) VALUES (?, ?, ?)");

    $stmt->execute([$_SESSION['user_id'], $score, $totalQuestions]);


    echo $score;

} ? >


view_questions.php:

<?php

session_start();

require 'db.php';


if ($_SESSION['role'] !== 'admin') {

    header("Location: dashboard.php");

    exit;

}


$stmt = $pdo->query("SELECT * FROM questions");

$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>


<table border="1">

    <tr>

        <th>ID</th>

        <th>Question</th>

        <th>Options</th>

        <th>Correct Option</th>

    </tr>

    <?php foreach ($questions as $question): ?>

    <tr>

        <td><?= $question['id'] ?></td>

        <td><?= $question['question_text'] ?></td>

        <td>

            <?= $question['option1'] ?><br>

            <?= $question['option2'] ?><br>

            <?= $question['option3'] ?><br>

            <?= $question['option4'] ?>

        </td>

        <td><?= $question['correct_option'] ?></td>

    </tr>

    <?php endforeach; ?>

</table>

<a href="dashboard.php">Back to Dashboard</a>


Download complete source code:

Download







Comments

Popular posts from this blog

Microsoft Excel top functions.

  Microsoft Excel offers numerous functions to simplify data analysis and calculation. Here are some of the most commonly used and powerful functions: Basic Functions SUM : Adds values. =SUM(A1:A10) AVERAGE : Calculates the mean of numbers. =AVERAGE(A1:A10) IF : Performs logical tests and returns values based on conditions. =IF(A1>10, "Yes", "No") COUNT : Counts numeric values in a range. =COUNT(A1:A10) LEN : Returns the length of a text string. =LEN(A1) Lookup and Reference Functions VLOOKUP : Looks for a value in the first column and returns a value in the same row from another column. =VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]) HLOOKUP : Similar to Here are practical examples of common Excel functions and how they can be applied in real-life scenarios: 1. SUM Scenario: Calculate the total sales for a week. Example: A B Day Sales Monday 200 Tuesday 150 Wednesday 300 Thursday 250 Friday 100 ...

Creating Wages Sheet using Microsoft Excel

  Creating wages sheet using Microsoft Excel The DAYS360 function in Microsoft Excel calculates the number of days between two dates based on a 360-day year (commonly used in financial calculations). A 360-day year assumes each month has 30 days, simplifying interest and payment schedules. Syntax: DAYS360(start_date, end_date, [method]) Parameters: start_date : The starting date (required). Enter it as a valid date or reference a cell containing a date. end_date : The ending date (required). Enter it similarly to the start_date. method : Logical value (optional). FALSE (default): Uses the U.S. (NASD) method for date calculations. TRUE : Uses the European method. Key Differences Between Methods: U.S. (NASD) : Adjusts the start and end dates depending on whether they fall on the 31st of a month. European : Always treats the start and end dates as the 30th of the month if they are the 31st. Example Usage: Example 1: Calculate days using the U.S. method =DAYS360("01/01/2024", ...

How to use Microsoft Excel PMT function?

  To use the PMT function in Microsoft Excel, follow these steps: Steps to Use the PMT Function: Open Excel : Open your Excel workbook where you want to calculate the payment. Select a Cell : Click on the cell where you want the result (monthly payment). Enter the PMT Function : Use the formula syntax: =PMT(rate, nper, pv, [fv], [type]) Input Arguments : rate : Interest rate per period (e.g., for a monthly rate, divide the annual rate by 12). nper : Total number of payment periods. pv : Present value (loan amount or investment). fv (optional) : Future value, usually 0 for loans. type (optional) : Payment timing: 0 (default): End of the period. 1: Beginning of the period. Press Enter : Excel will calculate and display the periodic payment. Example 1: Monthly Loan Payment Problem: You take a loan of $15,000 with an annual interest rate of 5%, to be repaid over 3 years (36 months). What is the monthly payment? Steps: Select a cell and enter: =PMT(5%/12, 3*12, -...