Link to home
Start Free TrialLog in
Avatar of Bruno1990

asked on

How to display incorrect answers in html table?

Below I have 4 database tables, Session, Question, Answer and Option_Type.

**Session Table:**

    SessionId  SessionName
    1                      AAA

**Question Table:**

    SessionId   QuestionId       QuestionContent            OptionId
    1                 1                              What is 1+1 and 4+4             2
    1                 2                              Does 2+2 = 4                           26
    1                 3                              What is 3+3 and 5+5             3

**Answer Table:**

    AnswerId  SessionId QuestionId  Answer
    1                         1               1                       B
    2                         1               1                       C
    3                         1               2                       Yes
    4                         1               3                       A
    5                         1               3                       C


    OptionId OptionType
    1                   A-C
    2                   A-D
    3                   A-E
    4                   A-F
    .... goes up to 24 where it goes up to A-Z
    25               True or False
    26               Yes or No

Now in a jsfiddle here I have created a demo html table which you can see here

Now if you have a good look at the html table, you will realise that what I am trying to do is display the incorrect answers under the "Incorrect Answer" column.

So for example for Question 1:

 - Option type is A-D
 - Correct Answer is B, C
 - So Incorrect answers that should be dislayed in table is A and D

So my question is that how in my php script can I select the option_type for a question, display all of the possible answers and remove the correct answers, displaying only the incorrect answers? The layout of the table must be the same as the layout in the jsfiddle.

Below is the table output in the php script. At the moment it is displaying similar table as in jsfiddle except difference is that it is outputting correct answers, not incorrect answers.

$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, an.Answer, q.QuestionMarks 
       FROM Session s 
       INNER JOIN Question q ON s.SessionId = q.SessionId
       JOIN Answer an ON q.QuestionId = an.QuestionId AND an.SessionId = q.SessionId
       WHERE s.SessionName = ?
       ORDER BY q.QuestionId, an.Answer
       // prepare query
       // You only need to call bind_param once
       $stmt->bind_param("s", $assessment);
       // execute query
           // This will hold the search results
        $searchQuestionId = array();
        $searchQuestionContent = array();
        $searchAnswer = array();
        $searchMarks = array();
        // Fetch the results into an array
       // get result and assign variables (prefix with db)
       $stmt->bind_result($dbSessionId, $dbSessionName, $dbQuestionId, $dbQuestionContent, $dbAnswer, $dbQuestionMarks);
          while ($stmt->fetch()) {
            $searchQuestionId[] = $dbQuestionId;
            $searchQuestionContent[] = $dbQuestionContent;
            $searchAnswer[] = $dbAnswer;
            $searchMarks[] = $dbQuestionMarks;
    <form id="QandA" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    echo "<table border='1' id='markstbl'>
          <th class='questionth'>Question No.</th>
          <th class='questionth'>Question</th>
          <th class='answerth'>Incorrect Answer</th>
          <th class='answermarksth'>Penalty per Incorrect Answer</th>
    $previous_question_id = null;
    $rowspans = array_count_values($searchQuestionId);
    foreach ($searchQuestionContent as $key=>$question) {
        // removed logic, not necessary to set empty strings if you're skipping them
        echo '<tr class="questiontd">'.PHP_EOL;
        if ($previous_question_id != $searchQuestionId[$key]) {
            echo '<td class="questionnumtd" name="numQuestion" rowspan="'.$rowspans[$searchQuestionId[$key]].'">'.htmlspecialchars($searchQuestionId[$key]).'</td>' . PHP_EOL;
            echo '<td class="questioncontenttd" rowspan="'.$rowspans[$searchQuestionId[$key]].'">'.htmlspecialchars($question).'</td>' . PHP_EOL;
        echo '<td class="answertd" name="answers[]">';
        echo $searchAnswer[$key];
        echo '</td>' ;
        echo '<td class="answermarkstd"><input class="individualMarks" name="answerMarks[]" id="individualtext" type="text" /></td>' . PHP_EOL;
        // moved this to the end
        if ($previous_question_id != $searchQuestionId[$key]) {
            $previous_question_id = $searchQuestionId[$key];
            echo '</tr>';
            echo "</table>" . PHP_EOL;

Open in new window

At the moment the code above is showing the correct answers under the "Incorrect Answers" column, not the incorrect answers.
Avatar of arnold
Flag of United States of America image

To display the incorrect you would need to compare the data submitted to the correct answers list.  I might be missing it, but it is not clear that you have the check if the answers submitted on the form match the correct answers.

It is not clear to me whether the sql statement at the top is data based on user input or those are the correct answers.
Is your inner join query to get a list of questions with their correct answers?

You build the table/columns, though I seem to be missing where you might have to use intermediary variables $correct_answers, $wrong_answers for each question
Then once you complete the data validation for each question, you would output the row with the question, and distinction of whether some or all choices were correct, or there is at least one wrong answer.
Avatar of Bruno1990



I don't have any variables which set up correct and wrong answers. All I have is the correct answers stored in the "Answer" Table for each question, and the optionid in the "Question" table which by using "Option_Type" in the Option_Table will determined the option type used for each question. The code at the moment is displaying the correct answers for each question (The answers stored for each question in the "Answer" Table). But I don't have anything when it comes to storing incorrect answers per question.

I am in no rush so we can go through this slowly and I will be on my laptop most of the day today so if you can help me out it would be very greatful :)
You do not need to store incorrect answers.
You compare whether the response to each question includes only the correct answer and all the or react options.
I.e question 1, A is he correct answer. The user submitted B. since the user provided response is not the correct answer, you would out put.
Alternativly, you can use the option type based data for the answers, and then cycle through excluding the correct answer/answers.
Not sure I clearly understand what you are trying to do.
I will be back n couple of hours and explain what I need to do because I am in a rush to go somewhere

Sorry for lateness,

Ok if you look at the code in my question, what the code outputs from the query and displays in a html table are all of the exam's:

Question Numbers
Correct Answers (These are basically answers retrieved from the "Answer" column in the "Answer" Table)
Text input for "Marks Per Answer"
Total Marks

Here is a jsfiddle of what the table looks like for example:

Now what I want to do is alter the code in my question so that it displays the same information in the table but the only change is that except displaying the "Correct Answers" column and displaying the correct answers (which are the answers from the "Answer" column), I simply want to display a "Incorrect Answers" column and wanting to display the remaining answers for each question (So don't want to display answers from the "Answer" column in db)

So my question is what is best method in able to find remaining answers for each question and then be able to implement it in the main code (code in my question)?
You would need to use the option column that defines the type of answers i.e. A-D A-E A-F and convert them to A, B, C, D,.. etc. as appropriate, then you would compare each viable option against the Correct answer outputing only when it is not in the correct answer group.

Not sure why you would want to go through the "process" of identifying wrong answers. If you want to assign different weights/penalties to incorrect answers in certain question, a better and simpler approach would be to create a penalty/weight table that will have the question ID and the weight/penalty to an incorrect answer for the question.

This way you have the flexibility to alter the options i.e. currently you have A-D as the possible answers to question 1, you then decide that another option should be included changing the options to A-E. With your identification of incorrect answer, would require that you recaclulate/remark the incorrect answers. With the suggestion of adding a weight/penalty table the rules do not require any additional processing/alterations to your code.

Yeah your right you solution is better in order to be able to give penalties for each individual incorrect answer.

So should the penalty table in the db have these fields:


So really the only thing now is what is the best way to code it in order to be able to achieve and display what you have mentioned in the php script. Take your time if you wish , I know that your the only one that will be able to code it as I will really struggle with it
Avatar of arnold
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Me and my supervisor thought that teachers should set their own penalty marks for each question. But I really do like your method better because it saves the teacher from writing all the penalty points again for each incorrect answer as it does it automatically.

But this is how it should work.

The teacher decides whether they want to include penalty points or not (this should be done in the form of 2 buttons, if the user clicks on "No Penalty Points" button then in "Session_Penalty" table it will be displayed as below:

SessionId  PenaltyActive

1               0

If user clicks on "Activate Penalty Points" button. then "Session_Penalty" table will look like this:

SessionId  PenaltyActive

1               1

Now after the user has clicked on the "Activate Penalty Points" button, then it should do what you stated and store all of the data in the penalty multiplier table you was talking about.

But the algorithm on when the marks should be penalised is this:

If a question has 3 correct answers e.g A B and D and there are 6 Options e.g A, B, C, D, E, F.

If the student selects the same or less amount of answers as the number of correct answers. E.g If the user selected B, D, F, they won't be penalised for any incorrect marks due to the fact that they selected the right number of answers.

But if a student tries to cheat and select more answers. E.g in example above select 4 or 5 answers, then penalty marks should be issued (maybe half the marks of each correct answer or what you feel is best)

If they select all the answers, then they get an instant 0 marks for that question.

What do you think and can you show any sample code on how this can be coded please? In your own time, you don't have to rush as I know you have other things to do
You could use the formula (number of submitted answers - number of correct answers) *multiplier*penalty this will deal with applying penalties based on excessive selections.

I do not have a way to provide a code example.
Ok, I will mark your answer, I just need to ask that do you think it is a good idea to state that if user selects more answers, then cut their correct answers by half? Do you think that is good enough to penalise students for cheating?
If that is the rule, that is the rule.  Not sure i understand.  My suggestion with calculating a penalty was just an example.  The penalty is to prevent guessing.
Thank you for your help :)