如果在foreach中存在行并不起作用

时间:2018-04-21 09:03:06

标签: php mysql if-statement pdo foreach

我通过ajax提交html数据数组。我的表格如下:

<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>

数组和输入已按以下方式传递给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>

我想在行存在或不存在的情况下回显消息。但它不起作用。以下代码中的错误是什么。也许foreach子句引起了问题。请帮忙

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";
    }
}
}

我的数据库看起来像

enter image description here

1 个答案:

答案 0 :(得分:1)

请勿在查询中包含引号'。您也可以在循环中直接使用$item变量而不是$_POST["section_name"][$key]。更改您的代码如下:

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',$item);
$query->bindParam(':class_id', $_POST["class_id"]);
$query->execute();
$count = $query->fetchColumn();
    if ($count === 1)
    {
        echo "Section found";
    }
    else 
    {
        echo "Section is not found";
    }
}
}

因为你必须计算你的结果。如下更改您的查询:

$query =$con->prepare("SELECT COUNT(class_id) as total_ids FROM section WHERE class_id= ':class_id' && section_name ':section_name')");