Comparing values in PHP and MYSQL

I am have been attempting to compare values selected from a MYSQL to a PHP array. My problem is that I can print out the array to see the values but i am not sure how to compare the MYSQL values to what is in the array. As in the code i have provided i have attempted to use an if else statement but does not work how i expected to as it does not compare the answer but still echos out the use response is incorrect . I would really appreciate it someone could look over my code and give me some guidance as to where i am going wrong.

I have included the two php pages i am currently working with

Answer Question Page

		   
	<?php
     require_once ('mysqli_connect.php');
	 
$q = "SELECT * FROM multiplechoice_db ORDER BY RAND() LIMIT 2";		
$result = @mysqli_query ($dbcon, $q); // Run the query
if ($result) { // If it ran OK, display the records
?>
<form action="answerquiz.php" method="GET">
<table>
<tr>
<td><b> For Each Question There will Only Be One Possible Answer</b> </td>
<br>
</tr>
<?php
// Fetch and print all the records
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$question = $row['question'];
$question_id = $row['question_id'];
$option_1 = $row['option_1'];
$option_2 = $row['option_2'];
$option_3 = $row['option_3'];
$option_4 = $row['option_4'];
?>
<tr>
<tr>
<td>
<br>
<br>

<ol><li><?php echo $question;?></li></ol>

1.<input type="radio"   name = "question_id[<?php echo $question_id;?>]" value= "1" /><?php echo $option_1;?> 
<br>
2.<input type="radio"   name = "question_id[<?php echo $question_id;?>]" value= "2" /><?php echo $option_2;?>  
<br>
3.<input type="radio"   name = "question_id[<?php echo $question_id;?>]" value= "3" /><?php echo $option_3;?> 
<br>
4.<input type="radio"   name = "question_id[<?php echo $question_id;?>]" value= "4" /><?php echo $option_4;?> 
<br>
<td>
<td>
<td>
<td>
</td>
</tr>
<?php
	}

?>


	 </table>
	<br>
	<input type ="submit" value="Submit Quiz">
	
	</form>

<?php	
}
	?>

answer_quiz page

 
require ('mysqli_connect.php');
if(isset($_REQUEST['question_id']) ){
    $arr_question_id = $_REQUEST['question_id'];
    //$question = '3';	
   // print_r($arr_question_id);

   $learner_response= "SELECT question_id, answer FROM multiplechoice_db WHERE question_id = 'question_id' AND answer = 'answer'";
   $result=@mysqli_query($dbcon, $learner_response);
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
   $question_id = $row['question_id'];
   $answer = $row['answer'];
   }
   $correct_answer=0;
   $incorrect_answer=0;
 
 //if ($result == FALSE)
//{
 //die(mysqli_error($dbcon));
 //}
 foreach($arr_question_id as $question_id=>$option_value){
 print " Question id: " .$question_id.    
       "Learner Response: ". $option_value.  "\
";
 }
 
      //while ($row = mysqli_fetch_array($result)) {
	  foreach($arr_question_id as $question_id=>$option_value){
       if($row['answer'] == $option_value){
	         echo ' You have answered the Question Correct';
             $correct_answer++;
           }else{
              echo ' You have answered the Question Incorrect';
              $incorrect_answer++;
          }
		   
		 
  "Numbers of correct answer : ". $correct_answer."<br>";
  "Numbers of correct answer  : ". $incorrect_answer."<br>";
}
}

The following line in your script doesn’t seem to make any sense:


$learner_response= "SELECT question_id, answer FROM multiplechoice_db WHERE question_id = 'question_id' AND answer = 'answer'";

Surely the question_id variable from the HTTP GET data should be used in the query, along with the answer provided? Hard-coding the values seems pretty useless to me.

Here’s a print_r of the HTTP data your answer quiz page should be receiving:


Array
(
	[question_id] => Array
	(
		[1] => 1
		[2] => 2
	)
	[submit] => Submit Quiz
)

(With the values in the question_id array subject to change according to what your quiz question query returns.)

So we can see that the keys of the question_id array are the keys of the random questions from the database, and they are pointing the user-submitted values. So let’s loop through the question_id array:


if(isset($_POST['submit'])) {
	foreach($_POST['question_id'] as $qID => $qVal) {
		// body
	}
}

(Note that I’ve changed your HTTP method to POST, since I believe it to be more suitable the GET in this instance.)

We now have a method of checking each question and its respective submitted answer, so let’s update the body of our foreach loop to query against the database:


if(isset($_POST['submit'])) {
	foreach($_POST['question_id'] as $qID => $qVal) {
		$qID = (int) $qID;
		$qVal = (int) $qVal;

		$learnerResponse= "SELECT COUNT(*) AS rightAnswer FROM multiplechoice_db WHERE question_id = {$qID} AND answer = {$qVal}";
		$result = mysqli_query($dbcon, $learnerResponse);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

		if($row['rightAnswer']) {
			// correct answer for question with ID of $qID
		}else{
			// wrong answer
		}
	}
}

Notice that I’ve casted the question ID and answer to integers (since that’s their type according to your quiz form) for security reasons. The query now gets a COUNT of the number of rows found for each submitted question and answer. If a row is found (i.e. a question and their respect answer matches), then a count of 1 will be returned, otherwise 0 will be returned.

Instead of using the LIMIT and ORDER BY clauses, consider the using array_rand()

Thanks for the help, you explanation was really helpful . I have one more question in relation to the if else statement I will be using. As in the code below if the answer the user gives is correct I want a statement to be printed out on the webpage telling the user they have got the question correct or if incorrect a statement they have got the question incorrect. I have ran the code the code you provided and added in the echo statements i wanted but I keep getting a blank page. Once again I am not sure what I am doing wrong as i have used php if else statements before without issue. Any guidance would be much appreciated.

 if($row['rightAnswer']){
	         echo ' You have answered the Question Incorrect';
            }else{
             echo ' You have answered the Question Incorrect';
           
          }

Could you execute the following instead of the above script (it just includes a var_dump() for debugging information and an ini setting to ensure errors are displayed) to help see what your problem is:


ini_set('display_errors', '1');
error_reporting(-1);
var_dump($_POST);
if(isset($_POST['submit'])) {
    foreach($_POST['question_id'] as $qID => $qVal) { 
        $qID = (int) $qID; 
        $qVal = (int) $qVal; 

        $learnerResponse= "SELECT COUNT(*) AS rightAnswer FROM multiplechoice_db WHERE question_id = {$qID} AND answer = {$qVal}"; 
        $result = mysqli_query($dbcon, $learnerResponse); 
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC); 

        if($row['rightAnswer']) { 
            // correct answer for question with ID of $qID 
        }else{ 
            // wrong answer 
        } 
    } 
} 

Once i run the above my output is:

array (size=1)
‘question_id’ =>
array (size=2)
11 => string ‘2’ (length=1)
2 => string ‘1’ (length=1)

I checked the answers to the two questions in the array against the matching id and answer in the database and they were both correct. However if I run the code with two answers I know are incorrect I get the same output. I have limited knowledge of php and arrays but I am starting to think that there might be an issue with the data actually reaching the if statement ?

The problem is that the body of the IF statement (checking to see if $_POST[‘submit’] is submitted) is not executing. This is because you haven’t named your submit button:


<input type="submit" name="submit" value="Submit Quiz">

Keep the script in my original post, but replace your submit button line with the above and things should work as expected.

It works !!! Thank you so much for all your help !!!