This question already has an answer here:
I got the following error when I try to display the post array element. How can I fix it?
Notice: Undefined index: ans in C:
Warning: Invalid argument supplied for foreach() in C:
HTML CODE
<input type = "radio" name = "ans[<?php echo $id; ?>]"
value="A"/>A. <?php echo $A; ?><br />
<input type = "radio" name = "ans[<?php echo $id; ?>]"
value="B"/>B. <?php echo $B; ?><br />
<input type = "radio" name = "ans[<?php echo $id; ?>]"
value="C"/>C. <?php echo $C; ?><br />
<input type = "radio" name = "ans[<?php echo $id; ?>]"
value="D"/>D. <?php echo $D; ?><br /><br />
PHP CODE
<?php
$db= new mysqli("localhost","root","","test");
if ($db->connect_error) {
echo "error connect database".$db-connect_error;
} else{
mysql_select_db("test") or die ("Unable to select database: " .mysql_error());
}
foreach($_POST['ans'] as $option_num => $option_val) {
echo $option_num." ".$option_val."<br>";
}
?>
</div>
You cannot use $_POST['ans']
because the values of your name attribute do not come as just 'ans'
. Instead, they are printed as 'ans' + the id you echoed
. For example, let's say your id in the option A of your answers is 1, we will then have 'ans[1]'
thus $_POST['ans[1]']
.
So, in general, you have to take care of that part of the string that makes your name attribute complete, which comes from <?php echo $id; ?>
, meaning if for example $id is 1, then name = "ans[<?php echo $id; ?>]"
will be the same as name = "ans[1]"
and you will request it as $_POST['ans[1]']
.
Hope this helps you out. You're welcome.