php在我的sql数据库中为每个选中的复选框插入多行


php insert multiple rows in my sql database for every checked checkbox

假设我有以下形式:

<form action="" method="post">
</BR>
<?php
// create two dropdowns with ajax
echo "<font id='"categoria'"><select>'n";
echo "<option value='0'>Select the Firm</option> 'n" ;
echo "</select></font>'n";
?>
<?php
echo "<font id='"subcategoria'"><select>'n";
echo "<option value='0'>Select the Claims Hub</option> 'n" ;
echo "</select></font>'n";
?>
<form method="post" align= "right">
<table >
    <tr><td>&nbsp;</td>
    <tr>
         <td style="text-align: left; ">Criminal  </td>
         <td align="left" >
            <input type="checkbox" name="mattertype" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
    <tr>
         <td style="text-align: left; ">Labour  </td>
         <td align="left" >
            <input type="checkbox" name="mattertype" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
    <tr>
         <td style="text-align: left; ">Civil  </td>
         <td align="left" >
            <input type="checkbox" name="mattertype" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
     <tr>
         <td style="text-align: left; ">Active  </td>
         <td align="left" >
            <input type="checkbox" name="active" value="1" />
         </td>
    </tr>   
    <tr><td>&nbsp;</td>
    <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="submit" value="Add" align= "right" /></td>
    </tr>
</table>

我将如何编写php代码来插入以下信息作为所有选中复选框的新记录?例如,我检查了Civil、Labour和Active。我现在想要第一条必须插入才能读取的记录

公司区域Mattertype活动(我的sql表)

类别的值子类别Civl 1的值
类别价值子类别价值人工1

如果勾选了任何或所有民事、劳工或刑事复选框,则必须插入类别值、子类别值、第一个勾选的复选框(物质类型),如果勾选"活动",则1表示"活动"。

然后,对于第二条记录,再次选择categoria的值、subcategoria值、第二个勾选的复选框(mattertype),如果勾选了active,则1表示active。

等等。我希望这是有道理的。

首先更改mattertype复选框以使用值的数组,并将每个值更改为唯一值(1表示犯罪,2表示劳工,3表示民事)

<input type="checkbox" name="mattertype[]" value="1" />
<input type="checkbox" name="mattertype[]" value="2" />
<input type="checkbox" name="mattertype[]" value="3" />

PHP

$categoria = $_POST['categoria'];
$subcategoria = $_POST['subcategoria'];
$mattertypes = $_POST['mattertype'];
$active = $_POST['active'] == 1 ? 1 : 0;
//$matertypes will be an array so loop over it
foreach( $mattertypes as $type ) {
  switch( $type ) {
     case '1':
       $typename = "Criminal";
     break;
     case '2':
       $typename = "Labour";
     break;
     case '3':
       $typename = "Civil";
     break;
  }
  $SQL = "INSERT into mytable (categoria,subcategoria,mattertype,active) VALUES('$categoria','$subcategoria','$typename','$active')";
  //Do the call to database with the query.
}

当然,在将数据放入数据库之前要对其进行清理。

在html

  <input type="checkbox" name="mattertype[]" value="1" />

在php中

//get mattertype which are checked by
$_POST['mattertype'];// this is come as array then use according to your requirement

将复选框名称设为name="mattertype[]"并更改值。

然后作为$_POST['mattertype']; 发布