user1964964
user1964964

Reputation: 255

Incorrect data displayed in html table

My output does not insert the data for Total Marks correctly, it seems like it is missing the total marks for question 1, This is because the marks for each question goes like this:

Question 1: 3
Question 2: 5
Question 3: 2

Now the table contains incorrect answers so the table looks like this fiddle which I have found http://phpfiddle.org/main/code/7j1-we2, if you look at the results, you realize that both question 1 and 2 contain question 2 marks and that queston 3 contains its marks. But how can I get the correct marks to be display, why is it missing the first question marks?

UPDATE 1:

$query = "SELECT q.QuestionNo, an.Answer, q.TotalMarks, o.OptionType
FROM 
Question q INNER JOIN Answer an ON q.QuestionID = an.QuestionID
INNER JOIN Option_Table o ON o.OptionID = q.OptionID
ORDER BY q.QuestionId, an.Answer
   ";

   // prepare query
   $stmt=$mysqli->prepare($query);
   // execute query
   $stmt->execute(); 


       // This will hold the search results
    $searchQuestionNo = array();
    $totalMarks = array();
    $incorrect_ans = array();


    // Fetch the results into an array

   // get result and assign variables (prefix with db)
$stmt->bind_result($dbQuestionNo, $dbAnswer, $dbTotalMarks $dbOptionType);

$specialOptionTypes = array('Yes or No' => array( 'Yes', 'No' ),'True or False' => array( 'True', 'False' ));

while ($stmt->fetch()) {

// Do this for each row:
if ( array_key_exists( $dbOptionType, $specialOptionTypes ) ) {
    $options = $specialOptionTypes[$dbOptionType];
} else if ( preg_match( '/^([A-Z])-([A-Z])$/', $dbOptionType, $match ) ) {
    $options = range( $match[1], $match[2] );
} else {
    // issue warning about unrecognized option type
    $options = array();
}
$right = str_split( $dbAnswer ); 
$wrong = array_diff( $options, $right );  

        $searchQuestionNo[] = $dbQuestionNo;
        $totalMarks[] = $dbQuestionMarks;
      }

Above is the code which retrieves the wrong answers. What happens is for each question, it retireves each questions $dbOptionType and display the list of possible answers. So for example if question 1's $dbOptionType is A - D, then the list of Answers it displays is A, B, C, D. Also the code above retrieves each question number and total marks using $dbQuestionNo and $TotalMarks.

If a question has multiple answers though, it displays two sets of answers and removes 1 answer from a set. This is because in the database, to recieve correct answer for a question which has multiple answers and single answers it is like this:

QuestionNo  Answer  TotalMarks OptionType
1           B       3          A-D
2           A       5          A-D
2           C       5          A-D
3           D       2          A-D

UPDATE 2:

For question 2 as it is multiple answers, that is why it is displays two sets of data in the arrays. Beause the way it is removing a correct answer if there are multiple answers in a question is as so:

Question 2: Answers: A, B, C, D  Remove Correct Answer: A  Incorrect Answers: B, C, D
Question 2: Answers: A, B, C, D  Remove Correct Answer: C  Incorrect Answers: A, B, D

The way it is removing correct answers if a question has multiple correct answers is above. It is:

To Remove second correct Answer it repeats the process:

UPDATE 3:

The error is caused by the fact that array you are iterating over $ques_ans with for() has a gap in keys.

var_dump($ques_ans) gives us:
array(3) {
  ... skipped for brevity
  [2]=>
  array(2) {
    [0]=>
    string(1) "B"
    [2]=>
    string(1) "D"
  }
  ... skipped for brevity
}

There is no element with the key 1. It's because the function array_intersect, which I use on line 49, preserves keys.

To quickly fix code just to make it work without errors I added array_values() on line 51: $ques_ans[$questionNo] = array_values($q_incorrect_ans); //store the array of incorrect ans against the ques no as key.

But I still get the odd gap in $keys.

HERE IS THE CODE:

Below is code:

   $query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionNo, q.QuestionContent, an.Answer, an.AnswerId, q.QuestionMarks, q.OptionId, o.OptionType 
FROM  
Question q INNER JOIN Answer an ON q.QuestionID = an.QuestionID 
INNER JOIN Option_Table o ON o.OptionID = q.OptionID 
INNER JOIN Session s ON s.Sessionid = q.Sessionid 
WHERE s.SessionName = ? 
ORDER BY q.QuestionId, an.Answer 
   "; 

   // prepare query 
   $stmt=$mysqli->prepare($query); 
   // You only need to call bind_param once 
   $stmt->bind_param("s", $assessment); 
   // execute query 
   $stmt->execute();  


       // This will hold the search results 
    $searchQuestionNo = array(); 
    $searchQuestionContent = array(); 
    $totalMarks = array(); 
    $searchAnswerId = array(); 
    $incorrect_ans = array(); 
    $searchMarks = array(); 

    // Fetch the results into an array 

   // get result and assign variables (prefix with db) 
$stmt->bind_result($dbSessionId, $dbSessionName, $dbQuestionId, $dbQuestionNo, $dbQuestionContent, $dbAnswer, $dbAnswerId, $dbQuestionMarks, $dbOptionId, $dbOptionType); 

$specialOptionTypes = array('Yes or No' => array( 'Yes', 'No' ),'True or False' => array( 'True', 'False' )); 

while ($stmt->fetch()) { 

// Do this for each row: 
if ( array_key_exists( $dbOptionType, $specialOptionTypes ) ) { 
    $options = $specialOptionTypes[$dbOptionType]; 
} else if ( preg_match( '/^([A-Z])-([A-Z])$/', $dbOptionType, $match ) ) { 
    $options = range( $match[1], $match[2] ); 
} else { 
    // issue warning about unrecognized option type 
    $options = array(); 
} 
$right = str_split( $dbAnswer );  
$wrong = array_diff( $options, $right );   

        $searchQuestionNo[] = $dbQuestionNo; 
        $searchQuestionContent[] = $dbQuestionContent; 
        $incorrect_ans[] = $wrong; 
        $searchAnswerId[] = $dbAnswerId; 
        $totalMarks[] = $dbQuestionMarks; 
        $searchMarks[] = $dbQuestionMarks; 
      }     

?> 



</head> 

<body> 

<?php

$ques_ans = array(); //to store incorrect answers against ques no.

$q_occ_count = array_count_values($searchQuestionNo);
foreach ($searchQuestionNo as $key => $questionNo) {
    if (!array_key_exists($questionNo, $ques_ans)) {
        if ($q_occ_count[$questionNo] === 1) //if a ques has only one correct ans
            {
            $ques_ans[$questionNo] = $incorrect_ans[$key]; //store the array of incorrect ans against the ques no as key 
        } else //if a ques has more than 1 correct ans
            {
            //find the intersection of incorrect_ans arrays for this ques
            $q_keys          = array_keys($searchQuestionNo, $questionNo);
            $q_incorrect_ans = $incorrect_ans[$q_keys[0]];
            foreach ($q_keys as $q_key) {
                $q_incorrect_ans = array_intersect($q_incorrect_ans, $incorrect_ans[$q_key]);
            }
            $ques_ans[$questionNo] = array_values($q_incorrect_ans); //store the array of incorrect ans against the ques no as key
        }
    }
}
var_dump($ques_ans);
?> 
<table id='penaltytbl'> 
<thead> 
<tr> 
<th class='questionth'>Question No.</th> 
<th class='questionth'>Question</th> 
<th class='incorrectanswerth'>Incorrect Answer</th> 
<th class='answermarksth'>Marks per Answer</th> 
<th class='totalmarksth'>Total Marks</th> 
<th class='noofmarksth'>Marks Remaining</th> 
</tr> 
</thead> 
<tbody> 
<?php

foreach ($ques_ans as $questionNo => $inc_ans) {
    $q_row_span = count($inc_ans);
    $row_count  = 0;

?> 

<tr class="questiontd"> 

<td class="questionnumtd q<?php
    echo $questionNo;
?>_qnum" rowspan="<?php
    echo $q_row_span;
?>"><?php
    echo $questionNo;
?> 
<input type="hidden" name="numQuestion" value="<?php
    echo $questionNo;
?>" /> 
    <input type="hidden" name="q<?php
    echo $questionNo;
?>_ans_org" class="q<?php
    echo $questionNo;
?>_ans_org" value="<?php
    echo $searchMarks[array_search($questionNo, $searchQuestionNo)];
?>"> 
    <input type="hidden" name="q<?php
    echo $questionNo;
?>_ans" class="q<?php
    echo $questionNo;
?>_ans" value="<?php
    echo $searchMarks[array_search($questionNo, $searchQuestionNo)];
?>"> 
    </td> 

    <td class="questioncontenttd" rowspan="<?php
    echo $q_row_span;
?>"><?php
    echo $searchQuestionContent[array_search($questionNo, $searchQuestionNo)];
?> </td> 

<td class="answertd"><?php
    echo $inc_ans[$row_count];
?> 
<input type="hidden" id="hiddenincorrect" name="incorrect[]" value="<?php
    echo $inc_ans[$row_count];
?>"> 
</td> 

<td class="answermarkstd"> 
<input class="individualMarks q<?php
    echo $questionNo;
?>_mark"  q_group="1" name="answerMarks[]" type="text" data-type="qmark" data-qnum="<?php
    echo $questionNo;
?>" onkeypress="return isNumberKey(event)" maxlength="3" /> 
</td> 


<td class="totalmarkstd" rowspan="<?php
    echo $q_row_span;
?>"><?php
    echo $totalMarks[array_search($questionNo, $searchQuestionNo)];
?></td> 

<td class="noofmarkstd q<?php
    echo $questionNo;
?>_ans_text"  q_group="1" rowspan="<?php
    $q_row_span;
?>"><?php
    echo "<strong>" . $searchMarks[array_search($questionNo, $searchQuestionNo)] . "</strong>";
?></td> 
</tr> 
    <?php
    //remaining incorrect answers in separate row (if any) follows here
    if ($row_count < $q_row_span - 1) {
        for ($i = ($row_count + 1); $i < $q_row_span; $i++) {
?>         
            <tr> 
            <td class="answertd"><?php
            echo $inc_ans[$i];
?> 
            <input type="hidden" id="hiddenincorrect" name="incorrect[]" value="<?php
            echo $inc_ans[$i];
?>"> 
            </td> 

            <td class="answermarkstd"> 
            <input class="individualMarks q<?php
            echo $questionNo;
?>_mark"  q_group="1" name="answerMarks[]" type="text" data-type="qmark" data-qnum="<?php
            echo $questionNo;
?>" onkeypress="return isNumberKey(event)" maxlength="3" /> 
            </td> 
            </tr> 
    <?php
        }
    }
}

?> 
</tbody> 
</table> 

<p> 
<input type='hidden' id='num_groups' name='num_groups' value='<?php
echo $questionNo;
?>'> 
<input id="submitBtn" name="submitPenalty" type="submit" value="Submit Marks" /> 
</p> 

</form>

SCREENSHOT:

enter image description here

Upvotes: 0

Views: 449

Answers (1)

ATOzTOA
ATOzTOA

Reputation: 35950

The issue is with the way you are retrieving the total marks. You are accessing $totalMarks with $questionNo as index, but should use the actual array index for that question.

Working code:

<td class="totalmarkstd" rowspan="<?php echo $q_row_span?>">
    <?php echo $totalMarks[array_search($questionNo, $searchQuestionNo)]?>
</td>

Update 1:

$ques_ans[$questionNo] = array_values($q_incorrect_ans);    //store the array of incorrect ans against the ques no as key

Update 2:

Use array_values.

foreach($ques_ans as $questionNo => $inc_ans)
{
    $inc_ans = array_values($inc_ans);

Updated phpFiddle: http://phpfiddle.org/main/code/get-rps

Upvotes: 1

Related Questions