Javascript 使用逗号分隔的复选框数组插入多个值

Javascript 使用逗号分隔的复选框数组插入多个值,javascript,php,mysql,arrays,insert,Javascript,Php,Mysql,Arrays,Insert,这是我现有的代码 我的数据库看起来像这样 req table test_id(auto increment) test_work varchar(50) <?php include_once '../connect.php'; //database connection if($_COOKIE["Utype"]!="Logistic") { header("Location: login.php"); } if(!isset($_POST['mat

这是我现有的代码 我的数据库看起来像这样

req table
test_id(auto increment)    test_work varchar(50)

<?php
include_once '../connect.php'; //database connection
if($_COOKIE["Utype"]!="Logistic")
{
                header("Location: login.php");
}

if(!isset($_POST['mat']))
{
     $checkboxValue = false;
} else {
     $checkboxValue = $_POST['mat'];
}

$values = implode(",", $_POST["mat"]);

$sql="Insert into req(test_work)
values ('$values')";
$result=mysql_query($sql);

?>


<script>
function toggle(source) {
  checkboxes = document.getElementsByName('mat[]');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}

$('input[type="checkbox"]').on('change', function(e){
        if($(this).prop('checked'))
        {
            $(this).next().val(1);
        } else {
            $(this).next().val(0);
        }
});

</script>
<form name="form" action="test.php" method="post">
<table border="1" width="200px" style="position:relative;top:0px;font-family:tahoma;font-size:12px;border-collapse:collapse">

<tr style="background-color:#f3f3f3">
<th width="2%"></th>
<th height="20px" width="15%">Work Order ID</th>
</tr>
<?php 
$resource=mysql_query("Select * from test",$con);

while($result2=mysql_fetch_array($resource))
    { 
    ?>
<tr style="background-color:#ffffff">
<td align="center"><input type="checkbox" name="mat[]" id="mat" value="<?php  echo $result2["id"]; ?>"/><?php  echo $result2["id"]; ?></td>
<td><?php  echo $result2["name"]; ?></td>
</tr>
<?php };?>
</table>
<input style="color:#FFFFFF;position:relative;width:70px"type="submit" name="submit" id="submit" value="Save" class="imgClass" height="50px">
</form>
当我只选中一个复选框时,它会忽略逗号

 req table
        test_id(auto increment)    test_work varchar(50)
        23                         1

因此,您不希望在req中插入一条记录,测试工作的值为'val1,val2,val3',而是希望它插入三条记录,值为'val1','val2','val3',对吗

在这种情况下,请尝试以下方法:

if(!isset($_POST['mat']))
{
    $checkboxValue = false;
} else {
    $checkboxValue = $_POST['mat'];
    foreach($_POST['mat'] as $val)
    {
        $query = "INSERT INTO req (test_work) VALUES ('$val')";
        mysql_query($query);
    }
}

这很有效。您的代码将选中多个复选框并生成一个字符串,如:1,2,5


这将在数据库中插入一行,“test_work”列的值为1,2,5。

代码看起来不错,您是否尝试过echo$sql;看看它是什么样子?你的更新还是不清楚。在代码中,您正在将数据插入一个名为test_work的列中,但您的更新调用了列mat_id。否,我需要它以逗号分隔。您需要哪一列以逗号分隔?材料id,还是测试工作?另外,列的数据类型和大小是什么?好的,我想我现在知道您需要什么了。测试工作列的数据类型和大小是什么?你好,rob先生?。。还在吗?
if(!isset($_POST['mat']))
{
    $checkboxValue = false;
} else {
    $checkboxValue = $_POST['mat'];
    foreach($_POST['mat'] as $val)
    {
        $query = "INSERT INTO req (test_work) VALUES ('$val')";
        mysql_query($query);
    }
}