0

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>";
    }
?>
James
  • 4,644
  • 5
  • 37
  • 48
Salmaho
  • 9
  • 1
  • 1
    The mysql_* extension that you've used was ***REMOVED*** from version 7 of PHP. You should now be using either the mysqli_* extension (note the "i" in there) or PDO and should also use prepared statements – SpacePhoenix Jun 17 '18 at 00:57
  • Does your form use GET or POST? If you're using GET that's why `$_POST` is empty. – Mike Jun 17 '18 at 04:18

1 Answers1

0

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.

ThunderBird
  • 283
  • 7
  • 13
  • Actually PHP automatically converts POST requests with square brackets in them to an array. `` will be used in PHP as `$_POST['ans']['1']`. – Mike Jun 17 '18 at 01:42