skip to Main Content

The purpose of the PHP code below is to create a math quiz consisting of two questions. The user will answer the two questions and click on the submit button.

After clicking the submit button, the user’s answers will be compared with the right answers (each question will be compared separately) then the total score $totalScore is calculated.

Finally, the user’s data will be inserted into the database then the user will be directed to a different webpage.

The only problem I have is the value for $totalscore, this value is either 1 or 0, whether the user answers all the questions right or wrong. it’s random. i don’t know why.

  • the value for $totalscore should be = 2 if user answers the two questions correctly
  • the value for $totalscore should be = 1 if user answers one of the questions correctly
  • the value for $totalscore should be = 0 if user answers the two questions incorrectly

But that is not the case. please help

<?php

get_header();

//GENERATING SOME RANDOM NUMBERS
$number1 = rand(1, 10); // Generate a random number between 1 and 10
$number2 = rand(1, 10); // Generate another random number between 1 and 10
$number3 = rand(1, 10); // Generate another random number between 1 and 10
$number4 = rand(1, 10); // Generate another random number between 1 and 10

// Calculate the answers for the two questions
$answer1 = $number1 + $number2;
$answer2 = $number3 + $number4;

$totalScore = 0; // Initialize total score
?>

<form method="post">
    <p>Question 1: What is <?php echo $number1; ?> + <?php echo $number2; ?>?</p>
    <input type="text" name="answerIn1" placeholder="Enter your answer" required><br>

    <p>Question 2: What is <?php echo $number3; ?> + <?php echo $number4; ?>?</p>
    <input type="text" name="answerIn2" placeholder="Enter your answer" required><br>

    <div class="centered-container-ForSubmitBtn">
        <input type="submit" name="submit_answer" value="Submit" style="border: 1px solid;">
    </div>
</form>

<?php
// Check if the form has been submitted
if (isset($_POST['submit_answer'])) {
    $userAnswers1 = $_POST['answerIn1']; // Get the user's answers from the submitted form for Q1
    $userAnswers2 = $_POST['answerIn2']; // Get the user's answers from the submitted form for Q2

    $user_name = $_SESSION['user_name']; // Retrieve the username from the session

    if ($userAnswers1 == $answer1) {
        $totalScore = $totalScore + 1;
    }

    if ($userAnswers2 == $answer2) {
        $totalScore = $totalScore + 1;
    }

    global $wpdb; // Access the global $wpdb object
    $table_name = $wpdb->prefix . 'My_user_test_info'; // Prefix the table name with the WordPress prefix

    // Prepare and execute the SQL query to insert the data into the database
    $data = array(
        'user_names' => $user_name,
        'test_scores' => $totalScore);
    $wpdb->insert($table_name, $data);

    //Direct the user to a different webpage
    wp_redirect(admin_url('/results-page/'));
}

?>


<?php
get_footer();
?>

I don’t have any other problems except for the one mentioned above.

2

Answers


  1. The issue with your code lies in the logic for calculating the total score. Currently, you are initializing the $totalScore variable to 0 at the beginning, but you never update it based on the user’s answers. As a result, the total score remains 0, and the value you receive is random.

    you need to update the $totalScore variable correctly based on the user’s answers.


    // Calculate the answers for the two questions
    $answer1 = $number1 + $number2;
    $answer2 = $number3 + $number4;
    
    $totalScore = 0; // Initialize total score
    
    // ...
    
    // Check if the form has been submitted
    if (isset($_POST['submit_answer'])) {
        // ...
    
        if ($userAnswers1 == $answer1 && $userAnswers2 == $answer2) {
            $totalScore = 2; // Both answers are correct
        } elseif ($userAnswers1 == $answer1 || $userAnswers2 == $answer2) {
            $totalScore = 1; // One answer is correct
        } else {
            $totalScore = 0; // Both answers are incorrect
        }
    
        // ...
    }
    

    the total score will be calculated correctly based on the user’s answers. If both answers are correct, the total score will be 2. If only one answer is correct, the total score will be 1. If both answers are incorrect, the total score will be 0.

    Also keep in mind if anything went wrong try to echo the variables you are testing

    Login or Signup to reply.
  2. Your numbers is getting changed every time user submits the form. You will need to store the numbers in session for matching with the users input.

    The final code will look like this.

    <?php
    session_start();
    get_header();
    // Check if the form has been submitted
    if (isset($_POST['submit_answer'])) {
        $totalScore = 0; // Initialize total score
        $userAnswers1 = $_POST['answerIn1']; // Get the user's answers from the submitted form for Q1
        $userAnswers2 = $_POST['answerIn2']; // Get the user's answers from the submitted form for Q2
    
        $user_name = $_SESSION['user_name']; // Retrieve the username from the session
    
        if ($userAnswers1 == $_SESSION['answer1']) {
            $totalScore = $totalScore + 1;
        }
    
        if ($userAnswers2 == $_SESSION['answer2']) {
            $totalScore = $totalScore + 1;
        }
    
        global $wpdb; // Access the global $wpdb object
        $table_name = $wpdb->prefix . 'My_user_test_info'; // Prefix the table name with the WordPress prefix
    
        // Prepare and execute the SQL query to insert the data into the database
        $data = array(
            'user_names' => $user_name,
            'test_scores' => $totalScore);
        $wpdb->insert($table_name, $data);
    
        //Direct the user to a different webpage
        wp_redirect(admin_url('/results-page/'));
    
    }else{
      //GENERATING SOME RANDOM NUMBERS
      $number1 = rand(1, 10); // Generate a random number between 1 and 10
      $number2 = rand(1, 10); // Generate another random number between 1 and 10
      $number3 = rand(1, 10); // Generate another random number between 1 and 10
      $number4 = rand(1, 10); // Generate another random number between 1 and 10
    
      // Calculate the answers for the two questions
      $answer1 = $number1 + $number2;
      $answer2 = $number3 + $number4;
      $_SESSION['answer1'] = $answer1;
      $_SESSION['answer2'] = $answer2;
    }
    
    ?>
    
    <form method="post">
        <p>Question 1: What is <?php echo $number1; ?> + <?php echo $number2; ?>?</p>
        <input type="text" name="answerIn1" placeholder="Enter your answer" required><br>
    
        <p>Question 2: What is <?php echo $number3; ?> + <?php echo $number4; ?>?</p>
        <input type="text" name="answerIn2" placeholder="Enter your answer" required><br>
    
        <div class="centered-container-ForSubmitBtn">
            <input type="submit" name="submit_answer" value="Submit" style="border: 1px solid;">
        </div>
    </form>
    
    <?php
    get_footer();
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search