Home > Software design >  Quiz in PHP, how to send a score with the mail form
Quiz in PHP, how to send a score with the mail form

Time:12-06

I have this quiz webpage created in PHP with some JavaScript code. It takes the input from the user (checked answers in the dropdown list), write them into another input box and uses the mail form to send the values from these input boxes to a specified email. It also checks the answers and gives the result in number of points with the click of the submit button (shows the result on the same page).

Problem #1: I would like to be able to send the score in the mail form too. How could I do it?

Problem #2: How could I pass the values from the dropdown list straight to the mail form to be sent later on with the click on submit (not to the input box as this code does now)?

Thanks for your help!

I habe not tried anything because I have no clue where to start. The way this quiz works out is the only way I have been able to come up with. I don´t have too much experience with coding, I am a beginner.

<!DOCTYPE HTML>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Quiz</title>
    </head>
    <body>
        <?php
            $message_sent = false;

            if (isset($_POST['answerq1']) && $_POST['answerq1'] != '')
            {
        
        
            //submit the form
            $Q1 = $_POST['answerq1'];
            $Q2 = $_POST['answerq2'];
            $Q3 = $_POST['answerq3'];
            $Q4 = $_POST['answerq4'];
            $Q5 = $_POST['answerq5'];
            $Q6 = $_POST['answerq6'];
            $Q7 = $_POST['answerq7'];
            $Q8 = $_POST['answerq8'];
            $Q9 = $_POST['answerq9'];
            $Q10 = $_POST['answerq10'];
            

            $messageSubject = $_POST['studentname'];
            $to = "[email protected]";
            $body = "";


           
            $body .= "Question 1: Your answer - ".$Q1. "*(A - CORRECT ANSWER)" . "\r\n".
            "1. What is the main purpose of the CPU? \n\nA. To process all the data and instructions \r\nB. To create PowerPoint presentations \r\nC. To provide power to the computer" ."\n\n" .
            "-----------------------------------".
            "\n\n";
            
            $body .= "Question 2: Your answer - ".$Q2. "*(True - CORRECT ANSWER)" . "\r\n".
            "The CPUs contain 100s of gold pins - some of these transmit data, others supply power to the CPU. \n\nA. True \r\nB. False" . "\n\n" .
            "-----------------------------------".
            "\n\n";
            
            $body .= "Question 3: Your answer - ".$Q3. "*(C - CORRECT ANSWER)" . "\r\n".
            "The CPU stands for: \n\nA. Central Process Unity \r\nB. Central Processing Utility \r\nC. C. Central Processing Unit" . "\n\n" .
            "-----------------------------------".
            "\n\n";

            $body .= "Question 4: Your answer - ".$Q4. "*(False - CORRECT ANSWER)" . "\r\n".
            "The RAM memory stands for Read Access Memory. \n\nA. True \r\nB. False" . "\n\n" .
            "-----------------------------------".
            "\n\n";

            $body .= "Question 5: Your answer - ".$Q5. "*(C - CORRECT ANSWER)" . "\r\n".
            "Which from below is NOT a component of the computer system? \n\nA. Sound card \r\nB. Hard drive \r\nC. Calculator" . "\n\n" .
            "-----------------------------------".
            "\n\n";
            
            $body .= "Question 6: Your answer - ".$Q6. "*(True - CORRECT ANSWER)" . "\r\n".
            "The difference between computer hardware and software is that the hardware is the parts that can be physically touched and seen and the software is the set of instructions. \n\nA. True \r\nB. False" . "\n\n" .
            "-----------------------------------".
            "\n\n";
            
            $body .= "Question 7: Your answer - ".$Q7. "*(B - CORRECT ANSWER)" . "\r\n".
            "The volatile memory is computer memory that requires power to maintain the stored information; it retains its content while powered on but when the power is interrupted, the stored data is quickly lost. Which one is an example of the volatile memory? \n\nA. ROM \r\nB. RAM \r\nC. Hard drive" . "\n\n" .
            "-----------------------------------".
            "\n\n";
            
            $body .= "Question 8: Your answer - ".$Q8. "*(A - CORRECT ANSWER)" . "\r\n".
            "What is the immediate access store used for? \n\nA. It holds the data and programs that the CPU currently needs \r\nB. It controls and monitors communications between the computer and any hardware attached \r\nC. It carries out calculations and logic operations" . "\n\n" .
            "-----------------------------------".
            "\n\n";

            $body .= "Question 9: Your answer - ".$Q9. "*(B - CORRECT ANSWER)" . "\r\n".
            "What is clock speed measured in? \n\nA. Cycles per minute \r\nB. Cycles per second \r\nC. Cycles per hour" . "\n\n" .
            "-----------------------------------".
            "\n\n";
 
            $body .= "Question 10: Your answer - ".$Q10. "*(C - CORRECT ANSWER)" . "\r\n".
            "What does the arithmetic and logic unit do? \n\nA. It controls and monitors communications between the computer and any hardware attached \r\nB. It holds the data and programs that the CPU currently needs \r\nC. It carries out calculations and logic operations" . "\n\n" .
            "-----------------------------------".
            "\n\n";
                        
            $headers = "From: [email protected]" . "\r\n";
            mail($to,$messageSubject,$body,$headers);
                $message_sent = true;
        }
        else{

        }           
        ?>
        
        
        <?php
            echo "Good luck in this Quiz!";

            if(!empty($_POST)) {
                $selected1 = $_POST['ans1'];
                $selected2 = $_POST['ans2'];
                $selected3 = $_POST['ans3'];
                $selected4 = $_POST['ans4'];
                $selected5 = $_POST['ans5'];
                $selected6 = $_POST['ans6'];
                $selected7 = $_POST['ans7'];
                $selected8 = $_POST['ans8'];
                $selected9 = $_POST['ans9'];
                $selected10 = $_POST['ans10'];
            
                $correct = 0;
            
                if ($selected1 == "q1AnswerA") {
                    $correct  ;
                    echo "<p>Question 1 - Correct!</p>";
                } elseif ($selected1 == "q1") {
                    echo "<p>Question 1 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 1 - Incorrect!</p>";

                if ($selected2 == "q2AnswerA") {
                    $correct  ;
                    echo "<p>Question 2 - Correct!</p>";
                } elseif ($selected2 == "q2") {
                    echo "<p>Question 2 - You forgot to answer this question!</p>";
                } else
                echo "<p>Question 2 - Incorrect!</p>";
        
                if ($selected3 == "q3AnswerC") {
                    $correct  ;
                    echo "<p>Question 3 - Correct!</p>";
                } elseif ($selected3 == "q3") {
                    echo "<p>Question 3 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 3 - Incorrect!</p>";
                
                if ($selected4 == "q4AnswerB") {
                        $correct  ;
                    echo "<p>Question 4 - Correct!</p>";
                } elseif ($selected4 == "q4") {
                    echo "<p>Question 4 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 4 - Incorrect!</p>";

                if ($selected5 == "q5AnswerC") {
                        $correct  ;
                    echo "<p>Question 5 - Correct!</p>";
                } elseif ($selected5 == "q5") {
                    echo "<p>Question 5 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 5 - Incorrect!</p>";

                if ($selected6 == "q6AnswerA") {
                        $correct  ;
                    echo "<p>Question 6 - Correct!</p>";
                } elseif ($selected6 == "q6") {
                    echo "<p>Question 6 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 6 - Incorrect!</p>";

                if ($selected7 == "q7AnswerB") {
                        $correct  ;
                    echo "<p>Question 7 - Correct!</p>";
                } elseif ($selected7 == "q7") {
                    echo "<p>Question 7 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 7 - Incorrect!</p>";

                if ($selected8 == "q8AnswerA") {
                        $correct  ;
                    echo "<p>Question 8 - Correct!</p>";
                } elseif ($selected8 == "q8") {
                    echo "<p>Question 8 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 8 - Incorrect!</p>";

                if ($selected9 == "q9AnswerB") {
                        $correct  ;
                    echo "<p>Question 9 - Correct!</p>";
                } elseif ($selected9 == "q9") {
                    echo "<p>Question 9 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 9 - Incorrect!</p>";

                if ($selected10 == "q10AnswerC") {
                        $correct  ;
                    echo "<p>Question 10 - Correct!</p>";
                } elseif ($selected10 == "q10") {
                    echo "<p>Question 10 - You forgot to answer this question!</p>";
                } else
                    echo "<p>Question 10 - Incorrect!</p>";
                    
                //here the result is displayed
                    echo "<p>You got $correct answers correct!</p>";    
            } 
            else {
                echo "<p>Please take the quiz.</p>";
            }   
            
                
        ?>
        <hr>
        <form action="nameofthisfile.php" method="post">

            <p><h3>1. What is the main purpose of the CPU?</p></h3>
            <p>A. To process all the data and instructions</p>
            <p>B. To create PowerPoint presentations</p>
            <p>C. To provide power to the computer</p>
            <select name="ans1" id="q1">
                <option value="q1">Your answer</option>
                <option value="q1AnswerA">Answer A</option>
                <option value="q1AnswerB">Answer B</option>
                <option value="q1AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans1 onclick="myFunctionQ1()" value="Save my answer">
            <input type="text" name="answerq1" id="q1ans">
            <br>
            <br>
            <hr>

            <p><h3>2. The CPUs contain 100s of gold pins - some of these transmit data, 
                      others supply power to the CPU.</p></h3>
            <p>True</p>
            <p>False</p>
            <select name="ans2" id="q2">
                <option value="q2">Your answer</option>
                <option value="q2AnswerA">True</option>
                <option value="q2AnswerB">False</option>
            </select>
            <input type="button"  id=buttonans2 onclick="myFunctionQ2()" value="Save my answer">
            <input type="text" name="answerq2" id="q2ans">
            <br>
            <br>
            <hr>

            <p><h3>3. The CPU stands for:</p></h3>
            <p>A. Central Process Unity</p>
            <p>B. Central Processing Utility</p>
            <p>C. Central Processing Unit</p>
            <select name="ans3" id="q3">
                <option value="q3">Your answer</option>
                <option value="q3AnswerA">Answer A</option>
                <option value="q3AnswerB">Answer B</option>
                <option value="q3AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans3 onclick="myFunctionQ3()" value="Save my answer">
            <input type="text" name="answerq3" id="q3ans">
            <br>
            <br>
            <hr>

            <p><h3>4. The RAM memory stands for “Read Access Memory”.</p></h3>
            <p>True</p>
            <p>False</p>
            <select name="ans4" id="q4">
                <option value="q4">Your answer</option>
                <option value="q4AnswerA">True</option>
                <option value="q4AnswerB">False</option>
            </select>
            <input type="button"  id=buttonans4 onclick="myFunctionQ4()" value="Save my answer">
            <input type="text" name="answerq4" id="q4ans">
            <br>
            <br>
            <hr>

            <p><h3>5. Which from below is NOT a component of the computer system?</p></h3>
            <p>A. Sound card</p>
            <p>B. Hard drive</p>
            <p>C. Calculator</p>
            <select name="ans5" id="q5">
                <option value="q5">Your answer</option>
                <option value="q5AnswerA">Answer A</option>
                <option value="q5AnswerB">Answer B</option>
                <option value="q5AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans5 onclick="myFunctionQ5()" value="Save my answer">
            <input type="text" name="answerq5" id="q5ans">
            <br>
            <br>
            <hr>

            <p><h3>6. The difference between computer hardware and software is that the 
                      hardware is the parts that can be physically touched and seen and the 
                      software is the set of instructions.</p></h3>
            <p>True</p>
            <p>False</p>
            <select name="ans6" id="q6">
                <option value="q6">Your answer</option>
                <option value="q6AnswerA">True</option>
                <option value="q6AnswerB">False</option>
            </select>
            <input type="button"  id=buttonans6 onclick="myFunctionQ6()" value="Save my answer">
            <input type="text" name="answerq6" id="q6ans">
            <br>
            <br>
            <hr>

            <p><h3>7. The volatile memory is computer memory that requires power to 
                      maintain the stored information; it retains its content while powered on 
                      but when the power is interrupted, the stored data is quickly lost. Which 
                      one is an example of the volatile memory?</p></h3>
            <p>A. ROM</p>
            <p>B. RAM</p>
            <p>C. Hard drive</p>
            <select name="ans7" id="q7">
                <option value="q7">Your answer</option>
                <option value="q7AnswerA">Answer A</option>
                <option value="q7AnswerB">Answer B</option>
                <option value="q7AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans7 onclick="myFunctionQ7()" value="Save my answer">
            <input type="text" name="answerq7" id="q7ans">
            <br>
            <br>
            <hr>

            <p><h3>8. What is the immediate access store used for?</p></h3>
            <p>A. It holds the data and programs that the CPU currently needs</p>
            <p>B. It controls and monitors communications between the computer and any 
                  hardware attached</p>
            <p>C. It carries out calculations and logic operations</p>
            <select name="ans8" id="q8">
                <option value="q8">Your answer</option>
                <option value="q8AnswerA">Answer A</option>
                <option value="q8AnswerB">Answer B</option>
                <option value="q8AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans8 onclick="myFunctionQ8()" value="Save my answer">
            <input type="text" name="answerq8" id="q8ans">
            <br>
            <br>
            <hr>

            <p><h3>9. What is clock speed measured in?</p></h3>
            <p>A. Cycles per minute</p>
            <p>B. Cycles per second</p>
            <p>C. Cycles per hour</p>
            <select name="ans9" id="q9">
                <option value="q9">Your answer</option>
                <option value="q9AnswerA">Answer A</option>
                <option value="q9AnswerB">Answer B</option>
                <option value="q9AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans9 onclick="myFunctionQ9()" value="Save my answer">
            <input type="text" name="answerq9" id="q9ans">
            <br>
            <br>
            <hr>

            <p><h3> 10. What does the arithmetic and logic unit do?</p></h3>
            <p>A.   It controls and monitors communications between the computer and any 
                    hardware attached</p>
            <p>B.   It holds the data and programs that the CPU currently needs</p>
            <p>C.   It caries out calculations and logic operations</p>
            <select name="ans10" id="q10">
                <option value="q10">Your answer</option>
                <option value="q10AnswerA">Answer A</option>
                <option value="q10AnswerB">Answer B</option>
                <option value="q10AnswerC">Answer C</option>
            </select>
            <input type="button"  id=buttonans10 onclick="myFunctionQ10()" value="Save my answer">
            <input type="text" name="answerq10" id="q10ans">
            <br>
            <br>
            <hr>

            <input type="text" name="studentname" id="sname" placeholder="Your name">
            <input type="submit">
        </form>

        <script>
            function myFunctionQ1(){
                var q1ans = q1.options[q1.selectedIndex].text;
                document.getElementById("q1ans").value = q1ans; 
            }

            function myFunctionQ2(){
                var q2ans = q2.options[q2.selectedIndex].text;
                document.getElementById("q2ans").value = q2ans; 
            }

            function myFunctionQ3(){
                var q3ans = q3.options[q3.selectedIndex].text;
                document.getElementById("q3ans").value = q3ans; 
            }

            function myFunctionQ4(){
                var q4ans = q4.options[q4.selectedIndex].text;
                document.getElementById("q4ans").value = q4ans; 
            }

            function myFunctionQ5(){
                var q5ans = q5.options[q5.selectedIndex].text;
                document.getElementById("q5ans").value = q5ans; 
            }

            function myFunctionQ6(){
                var q6ans = q6.options[q6.selectedIndex].text;
                document.getElementById("q6ans").value = q6ans; 
            }

            function myFunctionQ7(){
                var q7ans = q7.options[q7.selectedIndex].text;
                document.getElementById("q7ans").value = q7ans; 
            }

            function myFunctionQ8(){
                var q8ans = q8.options[q8.selectedIndex].text;
                document.getElementById("q8ans").value = q8ans; 
            }

            function myFunctionQ9(){
                var q9ans = q9.options[q9.selectedIndex].text;
                document.getElementById("q9ans").value = q9ans; 
            }

            function myFunctionQ10(){
                var q10ans = q10.options[q10.selectedIndex].text;
                document.getElementById("q10ans").value = q10ans; 
            }
        </script>

    </body>
    </html>
    

CodePudding user response:

at first i recommended you to look into php arrays and how to loop them. This will make your code look shorter, cleaner and easier. I am sorry, but the code is a little mess and its hard to implement your features in it.

CodePudding user response:

Firstly, it would really help to somehow make the code a bit more readable and then I believe solutions for both of your problems would appear in front of you (or we may find it here).

Quiz definition

How about having one place, where the whole quiz is defined? Example:

$quiz = [
    ['question' => 'What is the main purpose of the CPU?',
     'answers' => [
        ['To process all the data and instructions', true], //first item is the answer text, second item is whether that answer is correct (true/false)
        ['To create PowerPoint presentations', false],
        ['To provide power to the computer', false],
    ]],
    //... repeat other questions
];

Functions

Don't be afraid of using functions in PHP. Notice how your code repeats itself in some parts; that calls for using functions.

If you have the quiz defined in an array like in the example above, you can use a function to generate the HTML, another function to check results, yet another function to compute user's score and yet another function to create an e-mail body!

Generating HTML

function generateHtml()
{
  echo '<form>';
  foreach ($quiz as $questionNo => $questionData) {
    echo '<label>' . $questionData['question'] . '</label>';
    echo '<select name="question[' . $questionNo . ']">';
    foreach ($questionData['answers'] as $answerNo => $answerData) {
      echo '<option value="' . $answerNo . '">' . $answerData[0] . '</option>';
    }
    echo '</select>';
  }
  echo '<input type="submit"></form>';
}

Score and e-mail body

function computeScore(bool $perCent)
{
  $score    = 0;
  $maxScore = count($quiz);
  
  foreach ($quiz as $questionNo => $questionData) {
    if (!isset($_POST['question'][$questionNo]) {
      continue;
    }

    $usersAnswer = $_POST['question'][$questionNo];

    if ($quiz[intval($questionNo)]['answers'][intval($usersAnswer)][1] === true) {
      $score  ;
    }
  }

  if ($perCent === true) {
    return sprintf('%.2f %%', (($score * 100) / $maxScore));
  } else {
    return sprintf('%d out of %d', $score, $maxScore);
  }
}

function findCorrectAnswer(int $questionNo)
{
  $answer = '';
  foreach ($quiz[$questionNo]['answers'] as $answerNo => $answerData) {
    if ($answerData[1] === true) {
      $answer = sprintf('%d: %s', $answerNo, $answerData[0]);
    }
  }
  return $answer;
}

function emailBody() {
  $body = '';
  foreach ($quiz as $questionNo => $questionData) {
    $usersAnswer = 'NO ANSWER';
    if (isset($_POST['question'][$questionNo]) {
      $usersAnswer = $_POST['question'][$questionNo];
    }

    $correctAnswer = findCorrectAnswer($questionNo);

    $body .= sprintf("Question %d: Your answer - ".%s. "*(%s)" . "\r\n%d. %s \n\n", $questionNo, $usersAnswer, $correctAnswer, $questionNo, $questionData['question']);
    foreach ($questionData['answers'] as $answerNo => $answerData) {
      $body .= sprintf("%d. %s\r\n", $answerNo, $answerData[0]);
    }
    $body .= "-----------------------------------\n\n";
  }

  $body .= "Your score: " . computeScore(false);

  return $body;
}

Report answers

function htmlReport()
{
  foreach ($quiz as $questionNo => $questionData) {
    $usersAnswer = null;
    if (isset($_POST['question'][$questionNo]) {
      $usersAnswer = intval($_POST['question'][$questionNo]);
    }

    if ($usersAnswer === null) {
      echo "<p>Question $questionNo - You forgot to answer this question!</p>";
    } elseif ($questionData['answers'][$usersAnswer][1] === true) {
      echo "<p>Question $questionNo - Correct!</p>";
    } else {
      echo "<p>Question $questionNo - Incorrect!</p>";
    }
    
  }
}

Result

Look how easy you can make it afterwards:

<!DOCTYPE HTML>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Quiz</title>
    </head>
    <body>
        <?php
            /* PUT ALL THE FUNCTIONS HERE */

            if (isset($_POST['question'])) {
                $messageSubject = $_POST['studentname'];
                $to = "[email protected]";
                $body = emailBody();
                $headers = "From: [email protected]" . "\r\n";
                mail($to,$messageSubject,$body,$headers);
                $message_sent = true;
                
                htmlReport();
            } else {
                echo "<p>Please take the quiz.</p>";
            }   
                
        ?>
        <hr>
        <?php generateHtml() ?>

    </body>
</html>

Now you are using values directly from the comboboxes (problem #2) and you can include score wherever you can call the function "score()" (problem #1).

Hope this answers it... Please remind me if there is any error in the code or something essential missing in the answer.

  • Related