Hi! Im a student and new to php. I hope someone can help me make my codes work. The error is “Undefined index: ans in…”
test.php form: (the submitted form)
I didnt include the other parts since its for the interface design
<form action="results.php" method="POST">
<div class="tabcontent">
<table class="table table-hover">
<tbody>
<?php $num=1; ?>
<?php while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$question = $row['question'];
$test_id = $row['test_id'];
$optiona = $row['optiona'];
$optionb = $row['optionb'];
$optionc = $row['optionc'];
$optiond = $row['optiond'];
?>
<div class="form-group">
<h3 name="q<?php echo $num;?>" style="text-indent: 40px;"><?php echo $num,'. ', $question; ?> </h3>
</div>
<div class="form-group">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
;<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</div>
<?php $num++; ?>
<?php
}
?>
</tbody>
</table>
</div>
<br>
<div class="form-group"><center>
<input class="btn btn-success" type="submit" name="submit" value="Submit"></center>
</div>
</form>
results.php form:
<?php
require 'core/init.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "palo";
$conn= mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Connection failed: ". mysqli_connect_error());
}
if(isset($_POST['submit'])) {
$ans = $_POST['ans'];
$score = 0;
if( !empty($ans)):
foreach($ans as $qID => $qVal) {
$qID = (int) $qID;
$qVal = (int) $qVal;
$learnerResponse= "SELECT COUNT(*) AS rightAnswer FROM tquestions WHERE test_id = $qID AND
correctanswer = $qVal";
$result=mysqli_query($conn, $learnerResponse);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if($row['rightAnswer']) {
$score++;
}
}
endif;
}
?>
What ive been attempting to do is to match and count the correct answers of the user to the answer in the database. Thank you in advance!