Reputation: 1
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];
}
?>
Upvotes: 0
Views: 160
Reputation: 448
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;
}
?>
Upvotes: 1
Reputation: 133360
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;
}
?>
Upvotes: 1