PHP如果条件不起作用

时间:2018-04-20 09:43:02

标签: php json if-statement

我的html表单

<form id="myForm">
    <label for="sel1">Select Class:</label>
    <select class="form-control" id="class_name">
    <?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>
    <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>
</form>

的Ajax

<script>
    $("#submit").click(function(){
        var class_id = $("#class_name").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},
            dataType: 'JSON',
            success: function(response){
                alert(response);
                $('#myForm')[0].reset();
                }
            });
    });
</script>

我通过ajax在数据库中插入数组数据。在没有实现任何条件的情况下插入数据成功。当我尝试实现if条件时,它不起作用。以下代码中的错误是什么

<?php
include "connect.php";
$class_id = $_POST['class_id'];
$section_name = $_POST['section_name'];
$section_name = implode(",",$section_name);
$query=$con->query("SELECT * FROM section") or die($con->error);
while($row=$query->fetch(PDO::FETCH_ASSOC)){
    if(($class_id==$row['class_id'])&&($section_name==$row['section_name'])){
        echo json_encode('Section -'.$section_name.' has already assigned in '.$class_id);
    }
    else{
        $query2=$con->query("INSERT INTO section(class_id,section_name) VALUES('$class_id','$section_name')") or die($con->error);
    echo json_encode($section_name);
    }
}
?>

1 个答案:

答案 0 :(得分:0)

你正在破坏$ _POST部分列表

$section_name = implode(",",$section_name);

因此这种情况可能无效:

$section_name==$row['section_name'] 

取决于您的$ _POST部分排序