复选框仅提交一个复选框值

时间:2017-08-27 19:07:55

标签: php jquery checkbox

我有一个带有多个复选框的表单,例如A,B,C,D。有时我会希望用户选择多个复选框,比如B和C.当我这样做时,我只会看到最后一个值' C'在数据库中。我如何修改下面的代码以便将BC提交到数据库?

FORM

<form id="myform" method="post" action="check_trash.php">
<input type="text" name="afam" require />

A<input type="checkbox"name="get_value[]" value="A">  
B<input type="checkbox" name="get_value[]" value="B">  
C<input type="checkbox"name="get_value[]" value="C">  
D<input type="checkbox" name="get_value[]" value="D">

<button id="subm" name="upload" style="color:#fff; padding:5px 66px" class="btn btn-success" ><b>Save</b></button>
</form>

Jquery的

$("#subm").click( function() {

$.post( $("#myform").attr("action"), $("#myform").serialize(), function(info){ $("#result").html(info); } );
clearInput();
});

$("#myform").submit( function() {
    return false;
});

function clearInput() {
$('#myform').each(function(){
this.reset();
});    
}

PHP

if(!empty($_POST["get_value"])){
foreach($_POST["get_value"] as $checkbox){
}
$name = $_POST['myname'];
$insert_query = "insert into trash (checkbox,name) values ('$checkbox','$name')";

$run_query = mysqli_query($con, $insert_query);
if($run_query){
    echo "Submitted successfully";
}
else {
    echo "failed";
}
}

else{
echo "<script>alert('Please select at least one option!')</script>";
}

2 个答案:

答案 0 :(得分:0)

使用serilizeArray()方法而不是serialize()

$.post( $("#myform").attr("action"),   $("#myform").serializeArray(), function(info){  $("#result").html(info); } );

答案 1 :(得分:0)

这是你想要的

<?php

if(!empty($_POST["get_value"]))
{
    $checkedOptions = '';
    foreach($_POST["get_value"] as $checkbox)
    {

        $checkedOptions .= $checkbox;

    }


    $name = $_POST['myname'];
    $insert_query = "insert into trash (checkbox,name) values ('$checkedOptions','$name')";

    $run_query = mysqli_query($con, $insert_query);
    if(!$run_query)
    {
        echo "Submitted successfully";
    }
    else 
    {
        echo "failed";
    }
}

else
{
    echo "<script>alert('Please select at least one option!')</script>";
}
?>