<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "popularcomputer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "<h2>Adding missing columns to student_exams table</h2>";
// Add time_taken column
$addTimeTaken = "ALTER TABLE student_exams
ADD COLUMN time_taken INT NULL COMMENT 'in minutes' AFTER end_time";
if ($conn->query($addTimeTaken) === TRUE) {
echo "<p>Successfully added time_taken column.</p>";
// Update existing records to calculate time_taken based on start_time and end_time
$updateTimeTaken = "UPDATE student_exams
SET time_taken = TIMESTAMPDIFF(MINUTE, start_time, end_time)
WHERE start_time IS NOT NULL AND end_time IS NOT NULL";
if ($conn->query($updateTimeTaken) === TRUE) {
echo "<p>Updated existing records with time_taken values.</p>";
} else {
echo "<p>Error updating time_taken: " . $conn->error . "</p>";
}
} else {
echo "<p>Error adding time_taken column: " . $conn->error . "</p>";
}
// Add total_questions column
$addTotalQuestions = "ALTER TABLE student_exams
ADD COLUMN total_questions INT NOT NULL DEFAULT 0 AFTER time_taken";
if ($conn->query($addTotalQuestions) === TRUE) {
echo "<p>Successfully added total_questions column.</p>";
} else {
echo "<p>Error adding total_questions column: " . $conn->error . "</p>";
}
// Add correct_answers column
$addCorrectAnswers = "ALTER TABLE student_exams
ADD COLUMN correct_answers INT NOT NULL DEFAULT 0 AFTER total_questions";
if ($conn->query($addCorrectAnswers) === TRUE) {
echo "<p>Successfully added correct_answers column.</p>";
// Update existing records to calculate correct answers from student_exam_answers table
$updateCorrectAnswers = "UPDATE student_exams se
SET correct_answers = (
SELECT COUNT(*)
FROM student_exam_answers sea
JOIN exam_questions eq ON sea.question_id = eq.id
WHERE sea.student_exam_id = se.id
AND (
(eq.question_type = 'mcq' AND sea.selected_option = eq.correct_option)
OR
(eq.question_type = 'descriptive' AND sea.marks_awarded = eq.mark)
)
)";
if ($conn->query($updateCorrectAnswers) === TRUE) {
echo "<p>Updated existing records with correct_answers values.</p>";
} else {
echo "<p>Error updating correct_answers: " . $conn->error . "</p>";
}
// Update total_questions based on exam_questions table
$updateTotalQuestions = "UPDATE student_exams se
SET total_questions = (
SELECT COUNT(*)
FROM exam_questions eq
WHERE eq.exam_id = se.exam_id
)";
if ($conn->query($updateTotalQuestions) === TRUE) {
echo "<p>Updated existing records with total_questions values.</p>";
} else {
echo "<p>Error updating total_questions: " . $conn->error . "</p>";
}
} else {
echo "<p>Error adding correct_answers column: " . $conn->error . "</p>";
}
// Close connection
$conn->close();
echo "<p><a href='student/exam-results.php'>Go to Exam Results</a></p>";
?>