I am submitting html data array through ajax. My form look like:
<form id="myForm">
<label for="sel1">Select Class:</label>
<select class="form-control" name="class_id" id="class_id">
<?php
$query=$con->query("SELECT * FROM class ORDER BY id ASC") or die($con->error);
while($row=$query->fetch(PDO::FETCH_ASSOC)){?>
<option value="<?php echo $row['id']?>"><?php echo $row['class_name']?></option>
<?php } ?>
</select>
<br />
<label>Add Section: </label>
<label class="checkbox-inline"><input type="checkbox" name="section_name" value="A">A</label>
<label class="checkbox-inline"><input type="checkbox" name="section_name" value="B">B</label>
<label class="checkbox-inline"><input type="checkbox" name="section_name" value="C">C</label>
<br />
</form>
Array and input has been passed as following way to php
<script>
$("#submit").click(function(){
var class_id = $("#class_id").val();
var section_name = [];
$("input[name='section_name']:checked").each(function(){
section_name.push(this.value);
});
$.ajax({
url: 'insert_section.php',
type: 'post',
data: {class_id:class_id,section_name:section_name},
success: function(data){
alert(data);
$('#myForm')[0].reset();
}
});
});
</script>
I am trying to echo message in case of row exist or not. But it doesn't work. What is error in following code. Maybe foreach clause caused problem. Please help
if(isset($_POST["section_name"])){
foreach ($_POST["section_name"] AS $key => $item) {
$query =$con->prepare("SELECT class_id, section_name FROM section WHERE class_id= ':class_id' && section_name ':section_name')");
$query->bindParam(':section_name',$_POST["section_name"][$key]);
$query->bindParam(':class_id', $_POST["class_id"]);
$query->execute();
$count = $query->fetchColumn();
if ($count === 1)
{
echo "Section found";
}
else
{
echo "Section is not found";
}
}
}
My database looks like