DEV Community

Emil Ossola
Emil Ossola

Posted on

How to Create an online examination system with PHP and MySQL

Are you sick of giving tests the old-fashioned way, with ink and paper? You can now build an online examination system with PHP and MySQL, that enables you to develop, deliver, and grade exams from the convenience of your personal laptop. There will be no more paper waste and time-consuming grading; only a simplified and effective testing process for all parties.

PHP is a user-friendly server-side scripting language that simplifies the process of creating websites, while MySQL is an open-source relational database management system is incredibly reliable and will keep your data protected and organized.

When you combine PHP and MySQL, you can build an adaptable, scalable, and secure online exam system, whether you're giving examinations for a small classroom or a large online course.

Image description

What are the requirements and features of the online examination system

It is essential to specify the needs and features of the online examination system before beginning construction. This entails being aware of the intended audience, the kinds of tests that will be given, and the qualities that are essential for successful test-taking. A question bank, automatic grading, the capacity to create and amend tests, and secure user identification are a few crucial elements to take into account.

The following stage is to choose the suitable tools and technologies once you have a firm grasp of the needs and features. Because they are adaptable, scalable, and well-supported by web hosting companies, PHP and MySQL are a great choice for creating an online test system. Web frameworks like Laravel or CodeIgniter, JavaScript libraries like jQuery, and CSS frameworks like Bootstrap are a few other tools and technologies that can be required.

In this tutorial, Lightly IDE will be our primary tool for creating the online testing system. You may easily construct PHP and MySQL projects with the help of the integrated programming environment (IDE) known as Lightly IDE, which comes with an online PHP compiler and a MySQL database.

Image description

Setting up the Environment

Setting up the environment is an essential step in creating an online examination system with PHP and MySQL. Here's how to do it in Lightly IDE:

Creating a PHP project and setting up MySQL in Lightly IDE

Creating a PHP project in Lightky IDE can be done in a few clicks. Like any other online services, you'll have to sign up or log in to use the service. Once you've done so, you can click to create a new project and select the PHP language from the list.

Image description

Once you've created a PHP project, open the project and click on the "Cloud Service" panel to create a MySQL cloud service. The service quota is available for free when you sign up for a subscription.

Image description

Creating the database schema

Once PHP and MySQL are installed and configured, the next step is to create the database schema. This involves designing the database tables and fields necessary to store exam and question data. Some of the tables you may need to create include tables for exams, questions, answers, and results. It is important to design the database schema with scalability and efficiency in mind.

Here's an example of a database schema for an online examination system with PHP and MySQL:

Table: exams
Columns:

  • exam_id (int, primary key)
  • exam_name (varchar)
  • exam_duration (int)
  • exam_status (enum)

Table: questions
Columns:

  • question_id (int, primary key)
  • exam_id (int, foreign key)
  • question_text (varchar)
  • question_type (enum)

Table: answers
Columns:

  • answer_id (int, primary key)
  • question_id (int, foreign key)
  • answer_text (varchar)
  • is_correct (bool)

Table: results
Columns:

  • result_id (int, primary key)
  • exam_id (int, foreign key)
  • user_id (int)
  • score (int)
  • start_time (datetime)
  • end_time (datetime)

The columns for the exam ID, name, duration, and status are present in this example's examinations table. The questions table has columns for the question text, question type, exam ID (which acts as a foreign key referencing the examinations table), and question ID. The answers table has columns for the question ID, answer ID, response text, and a Boolean flag indicating whether the answer is accurate (the question ID acts as a foreign key referencing the questions table).

The result ID, exam ID (which serves as a foreign key referencing the examinations table), user ID, score, start time, and end time are the last columns in the results table. Exam outcomes and performance can be tracked using this table throughout time.

Creating a MySQL database

To create a MySQL database and user in the command line, you can follow these steps:

Log in to MySQL as the root user:
mysql -u root -p

Create a new database:
CREATE DATABASE yourdatabasename;

Create a new user and grant privileges to the database:
CREATE USER 'yourusername'@'localhost' IDENTIFIED BY 'yourpassword';
GRANT ALL PRIVILEGES ON yourdatabasename.* TO 'yourusername'@'localhost';
Replace "yourusername" and "yourpassword" with your preferred username and password, and replace "yourdatabasename" with the name of your newly created database.

Flush the privileges to ensure that the changes take effect:
FLUSH PRIVILEGES;

Exit MySQL:
exit
Once the database and user have been created, you may connect to the database and begin working with data using PHP's mysqli_connect() function.

Establishing the connection between PHP and MySQL

To connect to the MySQL database, use the mysqli_connect() function in PHP. The function takes four parameters: the MySQL server name, the MySQL username, the MySQL password, and the name of the database to connect to. Here's an example:
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabasename";

// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connectionif (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

Once the connection is established, you can use PHP to perform MySQL queries to retrieve and store data in the database. For example, to retrieve data from the exams table, you can use the mysqli_query() function:
$sql = "SELECT * FROM exams";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// Output data of each rowwhile($row = mysqli_fetch_assoc($result)) {
echo "Exam ID: " . $row["exam_id"]. " - Name: " . $row["exam_name"]. "
";
}
} else {
echo "0 results";
}

Creating the User Interface

Creating a user interface for an online examination system involves designing and implementing various components such as login/registration forms, exam pages, result display, and other relevant features. In this example, we'll be using PHP and MySQL to develop the interface. Please note that this is a simplified example, and you may need to customize it further to fit your specific requirements.

Here's a step-by-step guide to creating a basic user interface for an online examination system:

Create the login and registration forms

Design and implement the login and registration forms using HTML and CSS. You can use the

tag to create the forms and style them using CSS. The forms should collect relevant information from the user, such as username, password, name, and email.

Here's an example of how you can design and implement the login and registration forms for an online examination system using HTML and CSS:

<!DOCTYPE html>
<html>
<head>
  <title>Online Examination System</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Online Examination System</h1>

    <!-- Login Form -->
    <div class="form-container">
      <h2>Login</h2>
      <form action="login.php" method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
      </form>
    </div>

    <!-- Registration Form -->
    <div class="form-container">
      <h2>Register</h2>
      <form action="register.php" method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="text" name="name" placeholder="Full Name" required>
        <input type="email" name="email" placeholder="Email" required>
        <button type="submit">Register</button>
      </form>
    </div>
  </div>
</body>
</html>

In the example above, we have two sections: the login form and the registration form. Both forms have their own

tags with respective action attributes that point to the PHP scripts (login.php and register.php) responsible for processing the form submissions.

Here's a simple CSS style (in a separate style.css file) to apply basic formatting to the forms:

.container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

h1 {
  margin-bottom: 20px;
}

.form-container {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 10px;
}

input[type="text"],
input[type="password"],
input[type="email"],
button {
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  font-size: 16px;
}

button {
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

This is a basic example to get you started. You can further enhance the design and add more fields as per your specific requirements. Additionally, make sure to implement server-side validation and security measures in your PHP scripts (login.php and register.php) to handle the form submissions securely.

Implement the login and registration functionality

Using PHP, validate the user input from the login and registration forms. Check if the username and password are correct for the login form, and if the user is already registered for the registration form. If the input is valid, perform the necessary database operations, such as inserting a new user record or querying the database for existing user credentials.

Here's an example of how you can validate the user input from the login and registration forms using PHP:

<?php
// Validate login form input
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["login"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Perform validation
    if (empty($username)) {
        $errors[] = "Username is required.";
    }

    if (empty($password)) {
        $errors[] = "Password is required.";
    }

    // Proceed with login if there are no errors
    if (empty($errors)) {
        // Perform login logic here
        // You can check the credentials against the database, set session variables, etc.
        // Redirect the user to the appropriate page
        header("Location: dashboard.php");
        exit;
    }
}

// Validate registration form input
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["register"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];
    $name = $_POST["name"];
    $email = $_POST["email"];

    // Perform validation
    if (empty($username)) {
        $errors[] = "Username is required.";
    }

    if (empty($password)) {
        $errors[] = "Password is required.";
    }

    if (empty($name)) {
        $errors[] = "Full name is required.";
    }

    if (empty($email)) {
        $errors[] = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    // Proceed with registration if there are no errors
    if (empty($errors)) {
        // Perform registration logic here
        // You can insert the user data into the database, send a confirmation email, etc.
        // Redirect the user to the login page or display a success message
        header("Location: login.php");
        exit;
    }
}
?>

In the example above, we first check if the form submission method is POST and if the corresponding submit button is clicked (e.g., "login" or "register"). Then, we retrieve the form input values ($_POST) for validation.

For the login form, we check if the username and password fields are empty. If they are, we add error messages to an $errors array. If there are no errors, you can perform the login logic, such as checking the credentials against the database and setting session variables.

For the registration form, we perform similar validations for the username, password, name, and email fields. Additionally, we use the filter_var function with the FILTER_VALIDATE_EMAIL flag to validate the email format. If there are no errors, you can perform the registration logic, such as inserting the user data into the database or sending a confirmation email.

After validating the input and performing the necessary logic, you can redirect the user to the appropriate page using the header() function or display error/success messages to the user.

Design the exam interface using HTML and CSS

Create the exam interface using HTML and CSS. This interface should display the questions one by one, along with the options for each question. You can use radio buttons or checkboxes for multiple-choice questions. Provide a submit button to submit the exam.

<!DOCTYPE html>
<html>
<head>
  <title>Online Examination System - Exam</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Online Examination System - Exam</h1>

    <form action="submit_exam.php" method="POST">
      <?php
      // Retrieve and display questions from the database
      // Replace this section with your database query to fetch questions

      // Example questions array (replace this with your actual data)
      $questions = array(
          array(
              'id' => 1,
              'question' => 'Question 1: What is the capital of France?',
              'options' => array('A. Paris', 'B. London', 'C. Rome', 'D. Madrid'),
          ),
          array(
              'id' => 2,
              'question' => 'Question 2: What is the chemical symbol for gold?',
              'options' => array('A. Au', 'B. Ag', 'C. Cu', 'D. Fe'),
          ),
          array(
              'id' => 3,
              'question' => 'Question 3: Who painted the Mona Lisa?',
              'options' => array('A. Leonardo da Vinci', 'B. Vincent van Gogh', 'C. Pablo Picasso', 'D. Michelangelo'),
          ),
      );

      foreach ($questions as $question) {
          $questionId = $question['id'];
          $questionText = $question['question'];
          $options = $question['options'];

          echo '<div class="question">';
          echo '<h2>' . $questionText . '</h2>';

          // Display options using radio buttons
          foreach ($options as $option) {
              echo '<label>';
              echo '<input type="radio" name="answer[' . $questionId . ']" value="' . $option . '" required>';
              echo $option;
              echo '</label>';
          }

          echo '</div>';
      }
      ?>

      <button type="submit">Submit Exam</button>
    </form>
  </div>
</body>
</html>

In the example above, we have an HTML form that wraps around the exam questions. Inside the form, we use PHP to retrieve and display the questions dynamically. You would replace the PHP section with your database query to fetch the questions from your database.

For each question, we display the question text using the

heading element. Then, we iterate through the options array and display each option as a radio button. We use the name attribute with array notation (answer[questionId]) to group the radio buttons for each question together. The required attribute ensures that the user selects an option for each question.

After displaying all the questions and options, we have a submit button at the bottom of the form. When the user clicks the submit button, the form data will be sent to the submit_exam.php script for further processing.

Remember to customize the exam interface according to your specific requirements, including the styling using CSS. You can modify the layout, colors, fonts, etc., to match the design of your online examination system.

Implement the exam functionality using PHP

Using PHP, retrieve the questions from the database and display them on the exam interface. Handle the submission of the exam form, validate the answers, and calculate the marks obtained. Store the user's answers and marks in the results table in the database.

Here's the code:

<?php
// Database connection details
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";

// Create a database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve questions from the database
$sql = "SELECT * FROM questions";
$result = $conn->query($sql);
$questions = array();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $questions[] = $row;
    }
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $answers = $_POST["answer"];
    $marks_obtained = 0;
    $total_marks = 0;

    // Validate answers and calculate marks
    foreach ($questions as $question) {
        $questionId = $question['id'];
        $correctAnswer = $question['correct_answer'];
        $userAnswer = $answers[$questionId];

        if ($userAnswer == $correctAnswer) {
            $marks_obtained++;
        }
        $total_marks++;
    }

    // Store user's answers and marks in the results table
    $user_id = 1; // Replace with the actual user ID from your system
    $exam_id = 1; // Replace with the actual exam ID from your system

    $sql = "INSERT INTO results (user_id, exam_id, marks_obtained, total_marks) VALUES ('$user_id', '$exam_id', '$marks_obtained', '$total_marks')";
    if ($conn->query($sql) === TRUE) {
        echo "Results stored successfully.";
    } else {
        echo "Error storing results: " . $conn->error;
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Online Examination System - Exam</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Online Examination System - Exam</h1>

    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
      <?php
      // Display questions and options
      foreach ($questions as $question) {
          $questionId = $question['id'];
          $questionText = $question['question'];
          $options = array($question['option1'], $question['option2'], $question['option3'], $question['option4']);

          echo '<div class="question">';
          echo '<h2>' . $questionText . '</h2>';

          // Display options using radio buttons
          foreach ($options as $option) {
              echo '<label>';
              echo '<input type="radio" name="answer[' . $questionId . ']" value="' . $option . '" required>';
              echo $option;
              echo '</label>';
          }

          echo '</div>';
      }
      ?>

      <button type="submit">Submit Exam</button>
    </form>
  </div>
</body>
</html>

In the above example, we establish a database connection using the provided credentials. Then, we retrieve the questions from the "questions" table in the database using an SQL query. The fetched questions are stored in the $questions array.

Upon form submission, we handle the answers provided by the user. We iterate through each question, compare the user's answer with the correct answer stored in the database, and calculate the marks obtained. The variables $marks_obtained and $total_marks keep track of the user's marks.

Next, we store the user's answers and marks in the "results" table of the database. The user ID and exam ID are hardcoded in this example, so please replace them with the actual values from your system. The SQL query inserts the data into the "results" table.

Finally, we display the exam interface with questions and options using the retrieved data. Each question is displayed with a corresponding set of radio buttons for options. The form is submitted to the same page ($_SERVER["PHP_SELF"]) for handling the form submission.

Display the result using HTML and CSS

Design a result page using HTML and CSS to display the marks obtained by the user. Retrieve the result from the database using PHP and display it on the result page.

Certainly! Here's an example of how you can design a result page using HTML and CSS to display the marks obtained by the user. You'll also find the PHP code to retrieve the result from the database and display it on the result page:

<!DOCTYPE html>
<html>
<head>
  <title>Online Examination System - Result</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Online Examination System - Result</h1>

    <?php
    // Database connection details
    $servername = "your_servername";
    $username = "your_username";
    $password = "your_password";
    $dbname = "your_dbname";

    // Create a database connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Retrieve the result from the database
    $user_id = 1; // Replace with the actual user ID from your system
    $exam_id = 1; // Replace with the actual exam ID from your system

    $sql = "SELECT marks_obtained, total_marks FROM results WHERE user_id = '$user_id' AND exam_id = '$exam_id'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $marks_obtained = $row['marks_obtained'];
        $total_marks = $row['total_marks'];

        // Display the result
        echo "<h2>Marks Obtained: $marks_obtained/$total_marks</h2>";
    } else {
        echo "Result not found.";
    }

    $conn->close();
    ?>

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

In the above example, we start by establishing a database connection using the provided credentials. Then, we retrieve the result from the "results" table in the database based on the user ID and exam ID. The result is stored in the $marks_obtained and $total_marks variables.

We then proceed to display the result on the result page. We use PHP to echo the marks obtained and total marks within the

heading element.

Please note that you should replace the user ID and exam ID variables ($user_id and $exam_id) with the actual values from your system.

Finally, we close the database connection and provide a link to navigate back to the dashboard page (dashboard.php).

Remember to customize the result page according to your specific requirements, including the styling using CSS. You can modify the layout, colors, fonts, etc., to match the design of your online examination system. You can also add additional features to enhance the user interface, such as a timer to track the exam duration, a progress bar to indicate the completion of the exam, and a navigation bar to switch between different sections of the online examination system.

Fixing any bugs or issues

Once testing is complete, it's essential to fix any bugs or issues that were identified during the testing phase. This involves debugging the code, resolving any errors, and making necessary adjustments to ensure that the system works as expected. It's important to ensure that the system is thoroughly tested again after any fixes or adjustments are made.

Once testing is complete and all bugs are fixed, it's time to deploy the system to a server. This involves setting up a web server, configuring the server environment, and uploading the system files to the server. It's important to ensure that the server meets the system requirements and that all necessary dependencies are installed. Additionally, it's essential to secure the server and ensure that the system is accessible only to authorized users.

Conclusion

Creating an online examination system with PHP and MySQL is a challenging but rewarding task. By following the steps outlined in this article, you can develop a system that is functional, user-friendly, and secure. Here's a summary of the key points discussed:

  • Planning is essential before starting the development process. It involves defining the requirements, selecting appropriate tools and technologies, and creating a project timeline.
  • Setting up the environment involves installing and configuring PHP and MySQL and establishing a connection between them.
  • Creating the user interface involves designing the layout and navigation, creating forms for user input, and implementing an authentication and authorization system.
  • Developing the functionality involves creating modules for creating, editing, and deleting exams and questions, grading exams, and displaying results.
  • Testing and deployment involve conducting functional and usability testing, fixing any bugs or issues, and deploying the system to a server.

Future improvements and enhancements to the online examination system could include features like automated test generation, adaptive testing, and integration with other educational systems.

We encourage readers to try out the online examination system developed using PHP and MySQL. By testing the system, you can gain a deeper understanding of how it works and identify any areas for improvement. We hope that this article has provided you with the knowledge and tools you need to develop a successful online examination system.

Read more: How to Create an online examination system with PHP and MySQL

Top comments (0)