skip to Main Content

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)" . "rn".
            "1. What is the main purpose of the CPU? nnA. To process all the data and instructions rnB. To create PowerPoint presentations rnC. To provide power to the computer" ."nn" .
            "-----------------------------------".
            "nn";
            
            $body .= "Question 2: Your answer - ".$Q2. "*(True - CORRECT ANSWER)" . "rn".
            "The CPUs contain 100s of gold pins - some of these transmit data, others supply power to the CPU. nnA. True rnB. False" . "nn" .
            "-----------------------------------".
            "nn";
            
            $body .= "Question 3: Your answer - ".$Q3. "*(C - CORRECT ANSWER)" . "rn".
            "The CPU stands for: nnA. Central Process Unity rnB. Central Processing Utility rnC. C. Central Processing Unit" . "nn" .
            "-----------------------------------".
            "nn";

            $body .= "Question 4: Your answer - ".$Q4. "*(False - CORRECT ANSWER)" . "rn".
            "The RAM memory stands for Read Access Memory. nnA. True rnB. False" . "nn" .
            "-----------------------------------".
            "nn";

            $body .= "Question 5: Your answer - ".$Q5. "*(C - CORRECT ANSWER)" . "rn".
            "Which from below is NOT a component of the computer system? nnA. Sound card rnB. Hard drive rnC. Calculator" . "nn" .
            "-----------------------------------".
            "nn";
            
            $body .= "Question 6: Your answer - ".$Q6. "*(True - CORRECT ANSWER)" . "rn".
            "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. nnA. True rnB. False" . "nn" .
            "-----------------------------------".
            "nn";
            
            $body .= "Question 7: Your answer - ".$Q7. "*(B - CORRECT ANSWER)" . "rn".
            "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? nnA. ROM rnB. RAM rnC. Hard drive" . "nn" .
            "-----------------------------------".
            "nn";
            
            $body .= "Question 8: Your answer - ".$Q8. "*(A - CORRECT ANSWER)" . "rn".
            "What is the immediate access store used for? nnA. It holds the data and programs that the CPU currently needs rnB. It controls and monitors communications between the computer and any hardware attached rnC. It carries out calculations and logic operations" . "nn" .
            "-----------------------------------".
            "nn";

            $body .= "Question 9: Your answer - ".$Q9. "*(B - CORRECT ANSWER)" . "rn".
            "What is clock speed measured in? nnA. Cycles per minute rnB. Cycles per second rnC. Cycles per hour" . "nn" .
            "-----------------------------------".
            "nn";
 
            $body .= "Question 10: Your answer - ".$Q10. "*(C - CORRECT ANSWER)" . "rn".
            "What does the arithmetic and logic unit do? nnA. It controls and monitors communications between the computer and any hardware attached rnB. It holds the data and programs that the CPU currently needs rnC. It carries out calculations and logic operations" . "nn" .
            "-----------------------------------".
            "nn";
                        
            $headers = "From: [email protected]" . "rn";
            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>
    

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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 putting the questions and answers in one place. If you want to edit question/answers, you don’t have to change the rest of the code.

    // This is an array of questions. Key is the index of the question, value is the question as a string.
    $questions = [
      0 => 'first question',
      1 => 'second question',
    ];
    
    // This is an array, where key is the key of the question, and array is an array of possible answers for that question.
    
    $answers = [
      0 => [
        0 => 'first answer for first question',
        1 => 'second answer for first question'
      ],
      1 => [
        0 => 'first answer for second question',
        1 => 'second answer for second question'
      ]
    ];
    
    $correct = [
      0 => 1, //correct answer for question 0 is "second answer for the first question
      1 => 1 //correct answer for question 1 is "second answer for the second question
    ];
    

    Functions

    Don’t be afraid of using functions in PHP. Notice how your code repeats itself in some parts; that calls for using functions, which are meant to do one single procedure.

    If you have the quiz defined in arrays 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($questions, $answers)
    {
      // Start of the form
      echo '<form action="quiz.php" method="POST">';
      // Loop through all questions
      foreach ($questions as $questionIndex => $questionText) {
        // Question text
        echo '<label>' . $questionText . '</label><br>';
        // Start a <select> that will contain all possible answers
        echo '<select name="question[' . $questionIndex . ']">';
        // Loop through all answers of the current question
        foreach ($answers[$questionIndex] as $answerIndex => $answerText) {
          echo '<option value="' . $answerIndex . '">' . $answerText . '</option>';
        }
        // Close <select>
        echo '</select><br><br>';
      }
      // Add a field for the student's name
      echo '<label for="STUDENT_NAME">Your name:</label><br><input id="STUDENT_NAME" type="text" name="studentname" value=""><br><br>';
      // Submit button and that's it
      echo '<input type="submit"></form>';
    }
    

    Score

    function computeScore($questions, $correct)
    {
      // Start with score 0
      $score = 0;
      // Maximum score is the number of questions
      $maxScore = count($questions);
      
      // Loop through all questions in the quiz
      foreach ($questions as $questionIndex => $questionText) {
        // If user did not answer this question, jump to the next question
        if (!isset($_POST['question'][$questionIndex])) {
          continue;
        }
      
        // Save user's answer (which is answer index)
        $usersAnswer = intval($_POST['question'][$questionIndex]);
      
        // If correct answer index equals user's answer, increase the score
        if ($correct[$questionIndex] === $usersAnswer) {
          $score++;
        }
      }
      
      // Score output
      return sprintf('%d out of %d (%.2f %%)', $score, $maxScore, (($score * 100) / $maxScore));
    }
    

    E-mail body

    function emailBody($questions, $answers, $correct) {
      // We start with empty body and build its text bit by bit
      $body = '';
      // Loop through all questions
      foreach ($questions as $questionIndex => $questionText) {
        // User's answer is -1, which means "did not answer"
        $usersAnswer = -1;
    
        // If the user did answer though, save the user's answer index
        if (isset($_POST['question'][$questionIndex])) {
          $usersAnswer = intval($_POST['question'][$questionIndex]);
        }
      
        // Now we save the correct answer index
        $correctAnswer = $correct[$questionIndex];
      
        // And add this text to the e-mail body
        $body .= sprintf(
          "Question %d: Your answer - %d *(%d - CORRECT ANSWER)rn%d. %s nn",
          $questionIndex,
          $usersAnswer,
          $correctAnswer,
          $questionIndex,
          $questionText
        );
    
        // Now we just add the text of all possible answers for that question
        foreach ($answers[$questionIndex] as $answerIndex => $answerText) {
          $body .= sprintf("%d. %srn", $answerIndex, $answerText);
        }
    
        //Horizontal rule
        $body .= "-----------------------------------nn";
      }
      
      // To the end of the e-mail we just append the user's score
      $body .= "Your score: " . computeScore($questions, $correct, false);
      
      // Done!
      return $body;
    }
    

    Report answers

    function htmlReport($questions, $correct)
    {
      // Loop through all questions
      foreach ($questions as $questionIndex => $questionText) {
        // User's answer is -1, which means "did not answer"
        $usersAnswer = -1;
    
        // If the user did answer though, save the user's answer index
        if (isset($_POST['question'][$questionIndex])) {
          $usersAnswer = intval($_POST['question'][$questionIndex]);
        }
    
        // Now we output text - did not answer / correct / incorrect
        if ($usersAnswer === -1) {
          echo "<p>Question $questionIndex - You forgot to answer this question!</p>";
        } elseif ($usersAnswer === $correct[$questionIndex]) {
          echo "<p>Question $questionIndex - Correct!</p>";
        } else {
          echo "<p>Question $questionIndex - 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
    /* REPLACE THIS LINE WITH DEFINITION OF VARIABLES $questions, $answers, $correct */
    
    /* REPLACE THIS LINE WITH ALL THE FUNCTIONS */
    
    // Main part of the code follows
    
    // If there is the 'question' field in POST form, it means the user submitted the quiz
    if (isset($_POST['question'])) {
        // Prepare and send e-mail
        $messageSubject = $_POST['studentname'];
        $to = "[email protected]";
        $body = emailBody($questions, $answers, $correct);
        $headers = "From: [email protected]" . "rn";
        mail($to,$messageSubject,$body,$headers);
    
        // Make a report of user's answers
        htmlReport($questions, $correct);
    } else {
        // If the quiz was not submitted yet, let's encourage the user to do so :)
        echo "<p>Please take the quiz.</p>";
    }   
    ?>
            <hr>
            <?php generateHtml($questions, $answers) ?>
        </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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search