0% found this document useful (0 votes)
9 views1 page

Submit Exam

The document is a PHP script that connects to a MySQL database to evaluate quiz answers submitted in JSON format. It retrieves the correct answers for each question, compares them with user-selected answers, and calculates the total number of correct responses. Finally, it outputs the total score and detailed results for each question in JSON format before closing the database connection.

Uploaded by

leecatmy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Submit Exam

The document is a PHP script that connects to a MySQL database to evaluate quiz answers submitted in JSON format. It retrieves the correct answers for each question, compares them with user-selected answers, and calculates the total number of correct responses. Finally, it outputs the total score and detailed results for each question in JSON format before closing the database connection.

Uploaded by

leecatmy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

<?

php
$conn = new mysqli("localhost", "alcy_39066488", "Xx8IjK9ucjR7BNC",
"alcy_39066488_mock_test");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$answers = json_decode(file_get_contents('php://input'), true);
$total = 0;
$results = [];
foreach ($answers as $qid_str => $selected) {
$qid = (int)$qid_str;
$sql = "SELECT correct_option, question_text FROM questions WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $qid);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$correct = $row['correct_option'];
$question_text = $row['question_text'];
$is_correct = ($selected == $correct) ? 1 : 0;
$total += $is_correct;
$results[] = [
'question_text' => $question_text,
'user_answer' => $selected,
'correct_answer' => $correct,
'is_correct' => $is_correct
];
}
}
echo json_encode(['total' => $total, 'results' => $results]);
$conn->close();
?>

You might also like