0

I have created a DB which consists of courses. Students logged in can choose the courses using a dynamic checkbox and submitting it via a form.

<form method="POST" action="checkbox.php">
<?php
$sql1 = "SELECT course_id FROM course WHERE sem ='" .$_POST['sem']."'";
$result = mysqli_query($conn,$sql1);
while($row = mysqli_fetch_array($result)) {
echo "<input type='checkbox' name='course_id[]'             value='{$row['course_id']}'>" . $row['course_id'];
}
?>
<br>    
<button ><span>Submit</span></button>                                             
</form>

The form calls the PHP which consists of an array to echo the values. But I am getting an error from the php which says "undefined index 12IS36"..Here 12IS36 is the course stored in the DB.

PHP Code

<?php
//connection
foreach($_POST['course_id'] as $course) {
echo $_POST[$course];   
}
?>
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – chris85 Apr 17 '16 at 16:36
  • `echo $_POST[$course];` => `echo $course;` (will output 12IS36, ... ) – fusion3k Apr 17 '16 at 16:38
  • Check that `$_POST[$course]` is populated first. This is open to SQL injections as well. – chris85 Apr 17 '16 at 16:38

2 Answers2

1

You should not use a value like an index ..

<?php
 //connection
  foreach($_POST['course_id'] as $course) {
     echo $_POST[$course];    // in this case you are using a value like an index
  }
?>

you should use instead

<?php
 //connection
  foreach($_POST['course_id'] as $course) {
     echo $course;    
  }
?>
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

Maybe this will help you, i've improved the code slightly and escaped the clause to stop SQL injections.

<form method="POST" action="checkbox.php">
    <?php
    $sem = mysqli_real_escape_string($conn, $_POST['sem']);
    $sql = mysqli_query($conn, "SELECT course_id FROM course WHERE sem='$sem'");
    while($row = mysqli_fetch_assoc($sql)) {
        echo "<input type='checkbox' name='course_id[]' value='{$row['course_id']}'> ".$row['course_id'];
    }
    ?>
    <br>
    <button><span>Submit</span></button>                                             
</form>

<?php
    //connection
    foreach($_POST['course_id'] as $course) {
        echo $course;   
    }
?>
Sickaaron
  • 448
  • 1
  • 12
  • 21