如果foreach中存在行,则无法工作

mnemlml8  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(327)

这个问题在这里已经有答案了

在mysql中何时使用单引号、双引号和反引号(13个答案)
两年前关门了。
我通过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";
    }
}
}

我的数据库看起来像

vawmfj5a

vawmfj5a1#

不包括引号 ' 在查询中。也可以直接使用 $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')");

相关问题