I am trying to implement a form in which a user is asked some questions which are stored in a database. The answers for the respective questions is also stored and the user to supposed to answer those in the text boxes provided (like an online test system). I want to store all the answers entered by the user in an array, while storing the values of the answer column of the database in another array. Comparing the values of the two arrays should give me the number of right answers. I referred to this question and have used the following codes. But the problem is that the result is showing an undefined offset error at the place where I use variable $i
to compare the two arrays. Please help me.
Code for form (giveexam.php):
<form id ="answersheet" name="answersheet" action="assessment.php" method="post">
<table border="1px">
<tr>
<!--td>sr_no</td-->
<td width="144">Question</td>
<td width="50">option1</td>
<td width="50">option2</td>
<td width="50">option3</td>
<td width="50">option4</td>
<td width="30">
<strong>ANSWER</strong></td>
</tr>
<?php
require_once("connection.php");
$query = "select * from mgmt";
$result = mysql_query($query, $connection);
if(!$result)
echo "ERROR: No results";
else
{
while($row = mysql_fetch_array($result))
{
?>
<tr>
<!--td><?php echo $row['eid'];?></td-->
<td><?php echo $row['question'];?></td>
<td><?php echo $row['op1'];?></td>
<td><?php echo $row['op2'];?></td>
<td><?php echo $row['op3'];?></td>
<td><?php echo $row['op4'];?></td>
<td><input type="text" name="ans[]"/></td>
</tr>
<?php }
} //end while
?>
</table>
<tr>
<td></td>
<td><input type="submit" value="submit" /></td>
</tr>
</form>
PHP file (assessment.php):
<?php
session_start();
$m=0;
//$c=0;
require_once("connection.php");
$query="select answer from mgmt";
$result=mysql_query($query, $connection);
$result_array=array();
while($row=mysql_fetch_assoc($result))
{$result_array[]=$row;}
$answer=array();
$answer[]=$_POST["ans"];
for($i=1;$i<4;$i++)
{
if($answer[$i]==$result_array[$i])
$m++;
}
echo $m;
?>